9

I'm writing some code that will be using NSMutableArray and storing int values within it, wrapped within NSNumbers.

I would like to confirm that querying an iOS NSArray or NSMutableArray using new NSNumbers with same values is legal, of if I need to explicitly iterate over the array, and check if each int value is equal to the value I want to test against?

This appears to work:

NSMutableArray* walkableTiles = [NSMutableArray array];    


[walkableTiles addObject:@(1)];
[walkableTiles addObject:@(2)];
[walkableTiles addObject:@(3)];


if([walkableTiles containsObject:@(1)])
{
    DLog(@"contains 1"); //test passes
}
if([walkableTiles containsObject:[NSNumber numberWithFloat:2.0]])
{
    DLog(@"contains 2");//test passes
}
if([walkableTiles containsObject:[NSNumber numberWithInt:3]])
{
    DLog(@"contains 3");//test passes
}
Alex Stone
  • 46,408
  • 55
  • 231
  • 407
  • What do you mean by *legal*? I'm pretty sure that `containsObject:` iterates over the array at some point. – dandan78 Dec 12 '13 at 16:59
  • 1
    Have you read the spec for containsObject? "This method determines whether anObject is present in the array by sending an isEqual: message to each of the array’s objects (and passing anObject as the parameter to each isEqual: message)." – Hot Licks Dec 12 '13 at 17:01
  • Instead of NSNumber numberWithint: you can use literals and use @(3) – Grzegorz Krukowski Dec 12 '13 at 17:11

2 Answers2

16

What you are doing is fine. Why wouldn't it be?

The containsObject: method actually iterates over the array and calls the isEqual: method on each object passing in the object you are checking for.

BTW - there is nothing special here about using NSNumber. It's the same with an array of any object type. As long as the object's class has a valid isEqual: method, it will work.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
2

Per the Apple's NSNumber documentation, you should use isEqualToNumber:

isEqualToNumber: Returns a Boolean value that indicates whether the receiver and a given number are equal. - (BOOL)isEqualToNumber:(NSNumber *)aNumber

Rufel
  • 2,630
  • 17
  • 15