Why NSNumber points to the same address when value are equals?

前端 未结 3 828
心在旅途
心在旅途 2020-12-10 15:39

Given the following code:

int firstInt, secondInt;

firstInt = 5;
secondInt = 5;

NSNumber *firstNumber = [NSNumber numberWithInt:firstInt];
NSNumber *second         


        
3条回答
  •  囚心锁ツ
    2020-12-10 16:08

    My design instinct tells me that, if the score's identity is important as distinct from its mere value, you should be sorting some kind of score object instead of plain NSNumbers.

    But that aside: In a pinch, you can use plain NSValue similarly to how you're using NSNumber. It's a little more work to get values out, but NSValue itself doesn't have the instance coalescing behavior NSNumber does for small values.

    Some code that exercises all three behaviors:

      // NSValues are always distinct:
      int foo = 5, bar = 5, outfoo, outbar;
      NSValue *one = [NSValue value:&foo withObjCType:@encode(int)];
      NSValue *two = [NSValue value:&bar withObjCType:@encode(int)];
    
      [one getValue:&outfoo];
      [two getValue:&outbar];
      NSLog(@"one: %@ %x = %d ; two: %@ %x = %d",
            [one class], one, outfoo,
            [two class], two, outbar);
    
      // by comparison with NSNumber behavior:
      NSNumber *three = [NSNumber numberWithInt:6];
      NSNumber *four = [NSNumber numberWithInt:6];
    
      NSLog(@"three: %@ %x = %d ; four: %@ %x = %d",
            [three class], three, [three intValue],
            [four class], four, [four intValue]);
    
      // except when the numbers are big:
      NSNumber *five = [NSNumber numberWithInt:8675309];
      NSNumber *six = [NSNumber numberWithInt:8675309];
    
      NSLog(@"five: %@ %x = %d ; six: %@ %x = %d",
            [five class], five, [five intValue],
            [six class], six, [six intValue]);
    

    On my mac this yields output like:

    one: NSConcreteValue 42a8d0 = 5 ; two: NSConcreteValue 42a920 = 5
    three: NSCFNumber 404380 = 6 ; four: NSCFNumber 404380 = 6
    five: NSCFNumber 1324d0 = 8675309 ; six: NSCFNumber 106e00 = 8675309
    

提交回复
热议问题