测试 NSMutableArray 是否包含字符串对象
我有一个 NSMutableArray ,其中包含一些 NSString 对象。如何测试数组是否包含特定的字符串文字?
我尝试了 [array containsObject:@"teststring"] 但这不起作用。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你所做的应该很好。例如,
为我正确记录“在索引 1”。两个可能的缺点:
indexOfObject
发送isEqual
消息来进行比较 - 您还没有在类别中替换此方法吗?NSNotFound
是否无法定位,而不是(比如)0。What you're doing should work fine. For example
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?NSNotFound
for failure to locate, and not (say) 0.与字符串文字进行比较仅适用于代码示例。在现实世界中,您经常需要与数组中的 NSString* 实例进行比较,在这种情况下 containsObject 会失败,因为它与对象而不是值进行比较。
您可以在您的实现中添加一个类别,该类别扩展了 NS(Mutable)Array,并带有一个方法来检查它是否包含字符串(或您需要比较的任何其他类型);
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);
您还可以使用谓词:
You may also use a predicate:
对于每个对象
for every object