n.evermind
n.evermind

Reputation: 12004

Check if something exists in an NSMutableArray

I have an NSMutableArray which can hold several objects. I would like to check if an object exists, and if so, alter it. I was wondering about checking it. I thought this would work:

if ([[[self.myLibrary objectAtIndex:1] subObject] objectAtIndex:1]) // do something

However, this will crash if there aren't any subObjects at index 1. So I guess the problem is that the above does not return nil if there isn't anything at this Index.

Is there another easy way to check or will I have to count through the array etc.? I know there are other posts on stackoverflow on this, but I haven't found a simple answer yet.

Any explanations / suggestions welcome. Thanks!

Upvotes: 11

Views: 26959

Answers (4)

user756245
user756245

Reputation:

No check simply using :

[myArray indexOfObject:myObject];

or

[myArray containsObject:myObject];

These methods check every object using isEqual.


For example:

NSUInteger objIdx = [myArray indexOfObject: myObject];
if(objIdx != NSNotFound) {
    id myObj = [myArray objectAtIndex: objIdx];
    // Do some alter stuff here
}

Upvotes: 48

smorgan
smorgan

Reputation: 21569

If this is a pattern you use a lot, you could add a category to NSArray called something like safeObjectAtIndex:, which takes an index, does the bounds checking internally:

-(id)safeObjectAtIndex:(NSUInteger)index {
  if (index >= [self count])
    return nil;
  return [self objectAtIndex:index];
}

Upvotes: 13

Mike Weller
Mike Weller

Reputation: 45598

Assuming the object you are using to search with and the actual object in the array are the exact same instance, and not two different objects that are equal according to an overridden isEqual: method, you can do this:

if ([array containsObject:objectToSearchFor]) {
    // modify objectToSearchFor
}

If the two objects are different instances which are equal according to isEqual:, you will have to use code like this:

NSUInteger index = [array indexOfObject:objectToSearchFor];
if (index != NSNotFound) {
    id objectInArray = [array objectAtIndex:index];
    // modify objectInArray
}

Upvotes: 3

brain
brain

Reputation: 5546

NSArray (which is the NSMUtableArray superclass) has lots of methods for finding objects. Have a look at the documentation.

You can either rely on the equals method (e.g. indexOfObject:) or provide a block (e.g indexOfObjectPassingTest:) which is pretty funky.

It's fairly common in Objective C to be using the Mutable version of a class but rely on methods in the non mutable superclass so it's always a good idea when checking the online documentation to look at the superclass.

Upvotes: 2

Related Questions