On Jul 18, 2009, at 22:52, BJ Homer wrote:

In order to preserve the contract of NSArrayController (which is that you can add any object with addObject:), I'd recommend doing something like this:

- (void)addObject:(id)object {
   if ([object respondsToSelector:@selector(setIndex:)] {
object.index = [NSNumber numberWithInt:[[self arrangedObjects] indexOfObject:object]];
   }
   [super addObject:object];
}

Well, that won't compile, which is the horse we rode in on.

Assuming that's been taken care of (via option a, b or c from earlier in the thread), then this is a valid way to write the method, but not for the reason you say.

Since NSArrayController has been subclassed, the OP can set a new API contract for the subclass, possibly one that says 'addObject' must be called with an object that responds to 'setIndex:', or possibly one that says 'addObject:' may not be called from outside the subclass at all, or possibly the more liberal one that your code implements. (Note that when you get here from 'add:', the object is known to be of the class corresponding to the array controller's 'entityName' parameter.)

Note that I call super's addObject: at the end. I have no idea what the implementation of NSArrayController's addObject: is, but it's always better to have things set up before you pass something along to super. Imagine, for example, that NSArrayController writes the object immediately to disk when added. Since you haven't set your index yet, it would be incorrect. (I don't think it actually writes anything to disk at that point, but you get the idea.)

You're right. I at least wasn't thinking about the super-ish aspects of this.


_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to