I’m using xCode 4.2, and going through the book “Programming in Objective C 2.0”
There is an exercise that involves implementing isEqual: method from the NSObject class.
The book says that the isEqual: method is triggered when the removeObjectIdenticalTo: method of the NSArray class is called. removeObjectIdenticalTo: ends up sending isEqual: message to all array members.
When I’m trying to implement this isEqual: method in my class AddressCard, and I use removeObjectIdenticalTo:, passing an object that is an instance of AddressCard class, however, my isEqual: method is not getting called. Although if I just use the isEqual: method on an instance of AddressCard explicitly, it does work.
Here is my isEqual: method from the AddressCard.m file
-(BOOL)isEqual: (id)object {
NSLog(@"I got called");
return NO;
}
When this code is fired in AddressBook.m
-(void) removeCard: (AddressCard *) theCard {
[book removeObjectIdenticalTo: theCard];
}
the isEqual: method listed above is not called.
I feel like I’m missing something important, but from all I’ve read and I know, I think that isEqual: MUST be called, unless removeObjectIdenticalTo: does not involve it anymore.
I have all respective methods defined in .h files too.
It sounds like the book is in error.
NSMutableArrayand other collections have some pairs of similar methods likeremoveObject:andremoveObjectIdenticalTo:with important differences in their meanings.The first tests whether the values of the objects in the collection are the same as the value of the passed-in object. In order to do this, an array calls
isEqual:on each object in the array. This allows every class to define for itself what “equality” to another object means, as you are doing for yourAddressCardclass. Details aboutremoveObject:can be found in its documentation:The
...IdenticalTo:methods deal with the actual identity in memory of the objects. They check whether the address of the passed-in object is the same as that of any in the collection. An array can find the address of the object without calling any methods on that object;isEqual:is not used here. Again, this is stated in the docs:Generally speaking, you will want
removeObject:much more often thanremoveObjectIdenticalTo:, since its meaning most closely matches the action you wish to perform: select the object whose value is the same as the supplied object’s.