[ACCEPTED]-Comparing objects in Obj-C-objective-c
Comparing objects in Objective-C works much 12 the same as in Java or other object-oriented 11 languages:
==
compares the object reference; in Objective-C, whether they occupy the same memory address.isEqual:
, a method defined on NSObject, checks whether two objects are "the same." You can override this method to provide your own equality checking for your objects.
So generally to do what you want, you 10 would do:
if(![myArray containsObject:anObject]) {
[myArray addObject:anObject];
}
This works because the Objective-C 9 array type, NSArray, has a method called containsObject:
which 8 sends the isEqual:
message to every object it contains 7 with your object as the argument. It does 6 not use ==
unless the implementation of isEqual:
relies 5 on ==
.
If you're working entirely with objects 4 that you implement, remember you can override 3 isEqual:
to provide your own equality checking. Usually 2 this is done by comparing fields of your 1 objects.
Every Objective-C object has a method called 9 isEqual:
.
So you would want to override this for 8 your custom object types.
One particular 7 important note in the documentation:
If two 6 objects are equal, they must have the 5 same hash value. This last point is particularly 4 important if you define isEqual: in a 3 subclass and intend to put instances of 2 that subclass into a collection. Make 1 sure you also define hash in your subclass.
== will compare the pointer, you need to 1 override
- (BOOL)isEqual:(id)anObject
Implement isEqual: and hash
Per the Apple documentation on NSObject you need to implement isEqual:
and hash
at 10 a minimum. Below you'll find one way to 9 implement object equality, of course how 8 to implement hash
enters the land of serious 7 debate here on StackOverflow, but this will 6 work. General rule - you need to define 5 what constitutes object equality and for 4 each unique object they should have a unique 3 hash. It is best practice to add an object 2 specific equality method as well, for example 1 NSString
has isEqualToString:
.
- (BOOL)isEqual:(id)object
{
BOOL result = NO;
if ([object isKindOfClass:[self class]]) {
CLPObject *otherObject = object;
result = [self.name isEqualToString:[otherObject name]] &&
[self.shortName isEqualToString:[otherObject shortName]] &&
[self.identifier isEqualToString:[otherObject identifier]] &&
self.boardingAllowed == [otherObject isBoardingAllowed];
}
return result;
}
- (NSUInteger)hash
{
NSUInteger result = 1;
NSUInteger prime = 31;
result = prime * result + [_name hash];
result = prime * result + [_shortName hash];
result = prime * result + [_identifier hash];
result = prime * result + _boardingAllowed;
return result;
}
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.