Objective c 检查数组中是否存在对象时出现问题?

Objective c 检查数组中是否存在对象时出现问题?,objective-c,nsmutablearray,Objective C,Nsmutablearray,在这里,我试图在数组中添加对象,并检查数组中是否存在对象。为此,我使用以下代码 NSInteger ind = [arrActionList indexOfObject:indexPath]; if (ind >= 0 ) { [arrActionList removeObjectAtIndex:ind]; } else { [arrActionList addObject:indexPath]; } 在这里,我认为我做得对。。首先,我检查索引。如果大于等于0,我将删除该

在这里,我试图在数组中添加对象,并检查数组中是否存在对象。为此,我使用以下代码

NSInteger ind = [arrActionList indexOfObject:indexPath];
if (ind >= 0 ) {
    [arrActionList removeObjectAtIndex:ind];
}
else {
    [arrActionList addObject:indexPath];
}
在这里,我认为我做得对。。首先,我检查索引。如果大于等于0,我将删除该对象,否则添加一个新对象

我的问题是,若找不到对象的索引,它会将一个垃圾值分配给我的整数变量。我想它应该是-1,但它不是我的下一行,我在其中删除对象抛出错误

ind=2147483647


任何帮助…

如果您以后不需要ind的值,您可以直接编写

if ( [arrActionList containsObject:indexPath] ) {
     [arrActionList removeObject:indexPath;
}
else {
    [arrActionList addObject:indexPath];
}
或者,使用

if (ind != NSNotFound) { ...
因为这就是2147483647的实际值——它根本不是一个“垃圾”值,它告诉你一些有用的东西。

可能会有帮助

简而言之,
indexOfObject:
如果指定的对象不在数组中,则返回常量
NSNotFound
NSNotFound
常量的值为0x7FFFFFFF,十进制为2147483647

如果您执行以下操作,则代码应正确运行:

NSInteger ind = [arrActionList indexOfObject:indexPath];
if (ind != NSNotFound) {
    [arrActionList removeObjectAtIndex:ind];
}
else {
    [arrActionList addObject:indexPath];
}