Testing if NSMutableArray contains a string object

后端 未结 5 561
醉酒成梦
醉酒成梦 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: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
    

提交回复
热议问题