On Jul 18, 2009, at 14:35, Brad Gibbs wrote:

- (void)addObject:(Building *)object {
        [super addObject:object];
object.index = [NSNumber numberWithInt:[[self arrangedObjects] indexOfObject:object]];
        NSLog(@"Added %@", [object description]);
}

to override NSArrayController's standard implementation and assign an index to the newly-created object, based on its index within the underlying array. The problem is the type for the argument in the method declaration. With the standard method signature:

- (void)addObject:(id)object

the runtime doesn't have a specific entity to look to for a definition, so it doesn't know that I really want to be adding a Building entity, which does have an index attribute, and it throws an error. If I change the method declaration to:

- (void)addObject:(Building *)object

it knows that the Building entity has an index attribute, so the error goes away. But, that means that I need to create separate NSArrayController subclasses to control the arrays of the Floor and Room entities. I'm hoping to find a method declaration that can look to the entity type of the objects that the array controller is controlling (as set in IB), so that I can use the same subclass for the Building, Floor and Room arrays.

Oh, I get it now.

The error you're getting is nothing to do with the "runtime". The type of the parameter variable is a compile time matter only.

If IndexedObject is the superclass of Building, Floor and Room, you can take care of this at compile time:

- (void)addObject:(IndexedObject *)object {
        [super addObject:object];
object.index = [NSNumber numberWithInt:[[self arrangedObjects] indexOfObject:object]];
}

If it's just an entity with no custom class, you have to just make the compiler stop complaining:

- (void)addObject:(id)object {
        [super addObject:object];
[object performSelector: @selector (setIndex:) withObject: [NSNumber numberWithInt:[[self arrangedObjects] indexOfObject:object]]];
}

Either way, you only need one NSArrayController subclass for all 3 cases.

If you wish, you can add a check that the passed object is of the correct class or entity.

Incidentally, it would be slightly more correct to use "NSNumber numberWithUnsignedInteger" -- because "indexOfObject:" actually returns a NSUInteger value, which is unsigned, and which is 64 bits in a 64-bit app. This is not going to be a problem unless you have more than 2 billion objects, but it's good to be prepared. :)


_______________________________________________

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