views:

167

answers:

3

Hi.

I have an array that I am trying to check wether or not an indexPath(.row) exists in.

I use this code:

if ([array containsObject:[NSNumber numberWithInt:indexPath.row]]){
    NSLog(@"Yep, it exists in there.");
}

the array consist of the numbers 3, 8 and 2. The index path loads numbers fromm 0 to 8 in a loop.

Can anybody see why this doesen't work?

+1  A: 

containsObject: uses isEqual:, but NSNumber's equality comparison method is isEqualToNumber: Your code is inadvertently using the inherited isEqual which is just comparing pointers.

I think you'll have to iterate over array yourself and use isEqualToNumber:

Jim
+1  A: 

The array had strings in it, not numbers :)

Thank you, Jim.

Emil
+1  A: 

Since the array contains strings, you should compare against strings. To create a numeric string, use -stringWithFormat:. So:

if ([array containsObject:[NSString stringWithFormat:@"%d", indexPath.row]]){
    NSLog(@"Yep, it exists in there.");
}

A better solution is to store NSNumber's in the array.

KennyTM
Yeah, I use that now. The array is loaded from a plist, so thats not possible (i think).
Emil
@Emil: It is possible. Choose "Number" in Types in the property list editor. Save as binary or XML format.
KennyTM
oh, I didn't know that.Thanks! :)
Emil