3

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...

2 Answers 2

9

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];
}
Sign up to request clarification or add additional context in comments.

Comments

7

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.