tags:

views:

180

answers:

2

Hi,

I have a NSMutableArray with a few NSString objects in , how can i test if it contains a particular string literal

i tried [array containsObject:@"teststring"] but it doesn't work.

Thanks

A: 

for every object

[(NSString *) [array objectAtIndex:i] isEqualToString:@"teststring"];
mihirpmehta
pls consider giving comment when you down vote a perfect right answer...
mihirpmehta
I downvoted because it's *not* the right answer. You don't need to manually iterate over the array, because indexOfObject works fine. This answer will always be slower (sending many messages, no access to internal representations), and far more cumbersome.I only downvote answers when I have myself posted another answer when it's unambiguously wrong.
Adam Wright
+1  A: 

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 again NSNotFound for failure to locate, and not (say) 0.
Adam Wright