1

I have an array of current animal objects that can be viewed by day - for example, monday will return all animals that are available on a monday, etc.

I also have an array of saved animal objects.

How do I ensure that the saved animals don't show up in the current animals list?

Something like, if the currentAnimal.name isEqual to savedAnimal.name?

I need the objects in both arrays so it is important to compare the .name properties, I think?

2 Answers 2

4

Override isEqual and hash to do a comparison on the name if that is what you consider to make the objects 'equal'.

- (BOOL)isEqual:(id)other {
    if (other == self)
        return YES;
    if (!other || ![other isKindOfClass:[self class]])
        return NO;
    return [((MyObject *)other).name isEqualToString:name];
}

and

- (NSUInteger)hash {
  return [name hash];
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your answer but I'm not getting this at all, and I don't even know what hash is. What's 'other' and what's 'self', and where are the arrays?
hash and isEqual are default methods that Objective-c use to test the equality of an object. Normally these do instance equality, i.e. if the objects are the same instance, however you are saying that you may have two different instances BUT if the name is the same then you consider them equal. By overriding the methods you can redefine what it means for the object to be equal. The runtime will call these methods automatically so you just need to implement them... other is passed to the method, all you are doing is doing the equality check on the name.
OK, thanks for that, I understand better now. I think the problem I'm having now is getting the reference to the object from the saved array into this method. Hopefully this will work!!!
If you implement these methods, then you can either do [myobject1 isEqual:myobject2] to see if they are equal OR if(![myarray containsObject:myobject]) { [myarray addObject:myobject]; }
0

You should use isEqual method if you want objects strictly equals or method isKindOfClass. Look at NSObject reference

2 Comments

I don't want strictly equals though do I? I only want one of the Objects properties to match, not all of them.
@Simon give you the exact answer you need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.