Testing if NSMutableArray contains a string object

后端 未结 5 485
醉酒成梦
醉酒成梦 2021-01-31 14:59

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

I tried

相关标签:
5条回答
  • 2021-01-31 15:34

    You may also use a predicate:

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF IN %@", theArray];
    BOOL result = [predicate evaluateWithObject:theString];
    
    0 讨论(0)
  • 2021-01-31 15:35

    for every object

    [(NSString *) [array objectAtIndex:i] isEqualToString:@"teststring"];
    
    0 讨论(0)
  • [array indexOfObject:object] != NSNotFound
    
    0 讨论(0)
  • 2021-01-31 15:42

    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.
    0 讨论(0)
  • 2021-01-31 15:46

    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
    
    0 讨论(0)
提交回复
热议问题