当值等于时,为什么NSNumber指向相同的地址? [英] Why NSNumber points to the same address when value are equals?
本文介绍了当值等于时,为什么NSNumber指向相同的地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出以下代码:
int firstInt, secondInt;
firstInt = 5;
secondInt = 5;
NSNumber *firstNumber = [NSNumber numberWithInt:firstInt];
NSNumber *secondNumber = [NSNumber numberWithInt:secondInt];
为什么在地球上这两个NSNumber实例指向同一个地址?
Why on Earth do those two NSNumber instances are pointing to the same address?
这让我发疯了!
当然,如果你将secondInt更改为'4',那么一切都按预期工作。
Of course, if you change secondInt to, say '4', all works as expected.
谢谢,$ b $bJérémy
Thanks, Jérémy
推荐答案
这可能是一个编译器优化或实现细节:因为NSNumber是不可变的,所以不需要它们是单独的实例。
This is likely either a compiler optimisation or an implementation detail: as NSNumber is immutable there's no need for them be separate instances.
编辑:可能是考虑它的实现优化。当随后使用相同的整数调用时,可能的numberWithInt返回一个单例。
probably an implementation optimisation thinking about it. Likely numberWithInt returns a singleton when called subsequently with the same integer.
这篇关于当值等于时,为什么NSNumber指向相同的地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文