Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing if NSMutableArray contains a string object

Tags:

iphone

nsarray

I have a NSMutableArray which contains a few NSString objects. How can I test if the array contains a particular string literal?

I tried [array containsObject:@"teststring"] but that doesn't work.

like image 330
tech74 Avatar asked Apr 23 '10 10:04

tech74


People also ask

What is difference between NSArray and NSMutableArray?

The primary difference between NSArray and NSMutableArray is that a mutable array can be changed/modified after it has been allocated and initialized, whereas an immutable array, NSArray , cannot.

Is NSMutableArray thread safe?

In general, the collection classes (for example, NSMutableArray , NSMutableDictionary ) are not thread-safe when mutations are concerned. That is, if one or more threads are changing the same array, problems can occur.

What is NSMutableArray Objective C?

The NSMutableArray class declares the programmatic interface to objects that manage a modifiable array of objects. This class adds insertion and deletion operations to the basic array-handling behavior inherited from NSArray . NSMutableArray is “toll-free bridged” with its Core Foundation counterpart, CFMutableArray .


2 Answers

What you're doing should work fine. For example

NSArray *a = [NSArray arrayWithObjects:@"Foo", @"Bar", @"Baz", nil]; NSLog(@"At index %i", [a indexOfObject:@"Bar"]); 

Correctly logs "At index 1" for me. Two possible foibles:

  1. indexOfObject sends isEqual messages to do the comparison - you've not replaced this method in a category?
  2. Make sure you're testing against NSNotFound for failure to locate, and not (say) 0.
like image 129
Adam Wright Avatar answered Sep 22 '22 23:09

Adam Wright


[array indexOfObject:object] != NSNotFound 
like image 37
Bogdan Avatar answered Sep 18 '22 23:09

Bogdan