2

I wanted to have a list or set which might contain two NSNumbers with the same integer value but it seems that memory is optimised so they are the same object.
e.g

NSNumber* n1=[NSNumber numberWithInt:10];
NSNumber* n2=[NSNumber numberWithInt:10];

then n1==n2;

Is there a way round this so that n1!=n2 ?

mark
  • 147
  • 10
  • 5
    Why do you want this ? Put another way: what's the problem you're having that needs solving ? – DarkDust Sep 14 '11 at 13:55
  • 1
    Related question: [NSNumber >= 13 won't retain. Everything else will](http://stackoverflow.com/questions/2533355/nsnumber-13-wont-retain-everything-else-will/2533440#2533440) –  Sep 14 '11 at 13:57
  • I'm with DarkDust on this one. The fact that n1==n2 makes no difference when adding them to an NSArray or NSSet; it would do the "right" thing in both cases. – Stephen Darlington Sep 14 '11 at 14:00
  • @Stephen is this correct? Doesn't NSArray have a rule that if an object already exists in the array (or another one that responds YES to isEqual:), it just doesn't do anything? – Javier Soto Sep 14 '11 at 14:03
  • Yeah, I agree with DarkDust. My answer deals with the addresses but OP’s problem might have another solution. –  Sep 14 '11 at 14:04
  • 1
    @Javier I don't think there's such a rule. I've not tested it, but wouldn't an NSArray that doesn't allow duplicates be the same as an NSSet? – Stephen Darlington Sep 14 '11 at 14:10
  • I'm not doing anything important, just learning cocoa and writing a simple numbers game to amuse my self. A Mutable set only holds distinct objects but there seems to be a NSCountedSet which would probably work. – mark Sep 14 '11 at 14:37

1 Answers1

4

Not really. Cocoa keeps a cache of small numbers (IIRC those that represents integers from 0 to 12), and tagged pointers will also prevent that.

If you really need that, one option is to create a class that boxes NSNumber instances. In this way you can guarantee that different instances of your class will have different addresses.