简体   繁体   中英

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:

  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.
[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 eg 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];

对于每个对象

[(NSString *) [array objectAtIndex:i] isEqualToString:@"teststring"];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM