Objective-c – problem with Checking if object is exist in Array or not

nsmutablearrayobjective-c

Here I am trying to add object in array and checking if object is exist in array or not. for that I am using following code..

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

Here I suppose that I am doing right.. first I am checking for the index. If it is >= 0 I am removing the object else add a new object.

My problem is if there is no index found for object it assigns a garbage value to my integer variable. I suppose it should be -1 but it isn't so my next line in which I am removing object throw error.

ind = 2147483647

Any help…

Best Solution

The Official Documentation might be helpful.

In a nutshell, indexOfObject: returns the constant NSNotFound if the specified object is not in the array. The NSNotFound constant has a value of 0x7FFFFFFF, which is equal to 2147483647 in decimal.

Your code should behave correctly if you do:

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