Testing if NSMutableArray contains a string object
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.
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:
indexOfObject
sendsisEqual
messages to do the comparison - you've not replaced this method in a category?- Make sure you're testing against
NSNotFound
for failure to locate, and not (say) 0.
[array indexOfObject:object] != NSNotFound
Comparing against string literals only works in code examples. In the real world you often need to compare against NSString* instances in e.g. an array, in which case containsObject fails because it compares against the object, not the value.
You could add a category to your implementation which extends NS(Mutable)Array with a method to check wether it contains the string (or whatever other type you need to compare against);
@implementation NSMutableArray (ContainsString)
-(BOOL) containsString:(NSString*)string
{
for (NSString* str in self) {
if ([str isEqualToString:string])
return YES;
}
return NO;
}
@end
You may also use a predicate:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF IN %@", theArray];
BOOL result = [predicate evaluateWithObject:theString];
for every object
[(NSString *) [array objectAtIndex:i] isEqualToString:@"teststring"];
精彩评论