Getting Index of an Object from NSArray?

hemant picture hemant · Sep 13, 2011 · Viewed 93k times · Source

i am trying to get index of an array through indexOfObject method as follows but when i try to log the value to test the index i get a garbage value.. for testing purposes i am having an array with values {57,56,58..} to get an index of lets say 56,

NSNumber *num = [NSNumber numberWithInteger:56];
NSInteger Aindex = [myArray indexOfObject:num];
NSLog(@" %d",Aindex);

the value i get is something like 2323421. what am i possibly doing wrong??

Answer

user866214 picture user866214 · Sep 13, 2011

The index returned by indexOfObject will be the first index for an occurence of your object. Equality is tested using isEqual method.
The garbage value you get is probably equal to NSNotFound.
Try testing anIndex against it. The number you are looking for isn't probably in your array :

NSNumber *num=[NSNumber numberWithInteger:56];
NSInteger anIndex=[myArray indexOfObject:num];
if(NSNotFound == anIndex) {
    NSLog(@"not found");
}

or log the content of the array to be sure :

NSLog(@"%@", myArray);