Here I am trying to add object in array and checking if object is exist in array or not. for that I am 开发者_C百科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...
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];
}
If you don't need the value of ind later on , you could just write;
if ( [arrActionList containsObject:indexPath] ) {
[arrActionList removeObject:indexPath;
}
else {
[arrActionList addObject:indexPath];
}
Alternatively instead of testing ind >=0, use
if (ind != NSNotFound) { ...
because that's what the value 2147483647 actually is - it's not a 'garbage' value at all, it's telling you something useful.
精彩评论