Testing if NSMutableArray contains a string object

≡放荡痞女 提交于 2019-12-03 04:06:44

问题


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.


回答1:


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.



回答2:


[array indexOfObject:object] != NSNotFound



回答3:


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



回答4:


You may also use a predicate:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF IN %@", theArray];
BOOL result = [predicate evaluateWithObject:theString];



回答5:


for every object

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


来源:https://stackoverflow.com/questions/2697749/testing-if-nsmutablearray-contains-a-string-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!