简体   繁体   English

是否可以有两个具有相同值的不同NSNumber对象?

[英]Is it possible to have 2 different NSNumber objects with the same value?

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. 我想要一个可能包含两个具有相同整数值的NSNumber的列表或集合,但似乎内存已优化,因此它们是同一对象。
eg 例如

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

then n1==n2; 然后n1 == n2;

Is there a way round this so that n1!=n2 ? 有没有办法解决这个问题,以便n1!= n2?

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. 可可保留一个小数字的缓存(IIRC那些表示0到12的整数),带标记的指针也可以防止这种情况。

If you really need that, one option is to create a class that boxes NSNumber instances. 如果确实需要,一种选择是创建一个包装NSNumber实例的类。 In this way you can guarantee that different instances of your class will have different addresses. 这样,您可以保证您的类的不同实例将具有不同的地址。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM