如何判断对象是否在NSArray中?

时间:2021-11-26 16:59:37

Is there a way to tell if a certain object is in an NSArray? The way I am adding objects to my array makes it possible for the same object to be added multiple times and I wanted to see if there was a way to see if it was already there (anywhere) in that array.

有没有办法判断某个对象是否在NSArray中?我将对象添加到数组的方式使得可以多次添加同一个对象,我想看看是否有方法可以查看该数组中是否已存在(任何地方)。

2 个解决方案

#1


43  

The NSArray containsObject: method is precisely for this purpose, its full signature being:

NSArray containsObject:方法正是为了这个目的,它的完整签名是:

- (BOOL)containsObject:(id)anObject

See the full NSArray Class Reference docs for more information.

有关更多信息,请参阅完整的NSArray类参考文档。

#2


11  

if([yourArray indexOfObject:yourObject] == NSNotFound) {
     // your object is not in here
}

Edit: middaparkas approach is way better (if you don't want the index …)!

编辑:middaparkas方法更好(如果你不想索引......)!

#1


43  

The NSArray containsObject: method is precisely for this purpose, its full signature being:

NSArray containsObject:方法正是为了这个目的,它的完整签名是:

- (BOOL)containsObject:(id)anObject

See the full NSArray Class Reference docs for more information.

有关更多信息,请参阅完整的NSArray类参考文档。

#2


11  

if([yourArray indexOfObject:yourObject] == NSNotFound) {
     // your object is not in here
}

Edit: middaparkas approach is way better (if you don't want the index …)!

编辑:middaparkas方法更好(如果你不想索引......)!