0

I would like to check if my NSMutableArray contains my custom object. But if I understand correct contains functions searches for the same object in array (placed at the same memory point)

if(![objectArray containsObject:objToCheck])
{
    [objectArray addObject:objToCheck];
}       

I know that objectArray has identical object with identical variable values compared to objToCheck, yet such if always returns false. Is there a way to check this without writing custom loop and comparing objects by their parameters?

4
  • Are you trying to find a specific object instance or an object that is a class member? Commented May 16, 2013 at 8:22
  • 1
    Depending on what you are trying to do, NSSet might be more useful. Commented May 16, 2013 at 8:23
  • I'm trying to find specific object, all objects in list are same class, So I would like to find object with same variable values Commented May 16, 2013 at 8:23
  • You might look at using a temporary NSSet. This class is designed for quickly testing set membership. You can create one very easily with setWithArray: Commented May 16, 2013 at 8:27

2 Answers 2

4

Override the [NSObject isEqual:] method (actually it's part of the NSObject protocol) of your custom object and check whatever instance variables make sense to you for an object to be considered equal.

Here's an Apple Cocoa Competency article on the subject.

Sign up to request clarification or add additional context in comments.

7 Comments

... and, as always, don't forget to override hash accordingly.
Would the default not simply use the object id?
@uchuugaka Yes the default implementation uses the object pointer to compare for equality; the OP however wants to use properties of the object itself to test for equality and this is where -isEqual: comes in. And BTW that isn't the object's "id".
Well what I read was "is there a way to do this without checking by an object's parameters" which says to me something different.
Overriding isEqual: will indeed work but could also be a very limited case. Other scenarios may require comparison by other means. Special casing is fine if that is the only use case.
|
0

You might try creating a temporary NSSet from your array and testing against that for membership.

2 Comments

Probably because the NSSet does not help in comparing the objects. NSArray's containsObject: can already check for membership. In this question it's the comparison that is missing.
NSSet membership is automatically unique object instances. NSArray can hold the same instance multiple times. Perhaps I've missed some angle in the problem.

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.