为什么NSNumber如此奇怪的keepCounts? [英] Why has NSNumber such strange retainCounts?

查看:78
本文介绍了为什么NSNumber如此奇怪的keepCounts?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

NSNumber* n = [[NSNumber alloc] initWithInt:100];
NSNumber* n1 = n;

在上面的代码中,为什么n的keepCount的值设置为2?在代码的第二行中,我没有使用keep来增加keepCount的数量.


我发现了一个奇怪的情况.实际上,retainCount取决于初始数字:

NSNumber *n = [[NSNumber alloc] initWithInt:100]; 
// n has a retainCount of 1

NSNumber *n2 = [[NSNumber alloc] initWithInt:11]; 
// n has a retainCount of 2

解决方案

基于此链接

根据您的更新,我确定为您提供的链接几乎可以确定是问题所在.有人进行了测试,发现从0到12的NSNumbers将为您提供已经创建的NSNumbers的副本(实际上,它们甚至可以在用户请求之前由框架创建).大于12的其他人似乎保留了1.报价:

根据我的检查,似乎可以得到[NS]整数NSNumbers的共享"版本,取值范围为[0-12].大于12的值都会获得一个唯一的实例,即使值相等.为什么十二点?没有线索.我什至不知道这是一个困难的数字还是偶然的.

尝试使用11、12和13进行尝试-我想您会发现13是第一个为您提供非共享NSNumber的人.

NSNumber* n = [[NSNumber alloc] initWithInt:100];
NSNumber* n1 = n;

In the code above, why is the value of n's retainCount set to 2? In the second line of the code, I didn't use retain to increase the number of retainCount.


I found a strange situation. Actually the retainCount depends on the initial number:

NSNumber *n = [[NSNumber alloc] initWithInt:100]; 
// n has a retainCount of 1

NSNumber *n2 = [[NSNumber alloc] initWithInt:11]; 
// n has a retainCount of 2

解决方案

Based on this link here, it's possible that there's some optimization going on under the covers for common NSNumbers (which may not happen in all implementations hence a possible reason why @dizy's retainCount is 1).

Basically, because NSNumbers are non-mutable, the underlying code is free to give you a second copy of the same number which would explain why the retain count is two.

What is the address of n and n1? I suspect they're the same.

NSNumber* n = [[NSNumber alloc] initWithInt:100];

NSLog(@"Count of   n : %i",[n retainCount]);

NSNumber* n1 = n;

NSLog(@"Count of   n : %i",[n retainCount]);
NSLog(@"Count of   n1: %i",[n1 retainCount]);
NSLog(@"Address of n : %p", n);
NSLog(@"Address of n1: %p", n1);

Based on your update, that link I gave you is almost certainly the issue. Someone ran a test and found out that the NSNumbers from 0 to 12 will give you duplicates of those already created (they may in fact be created by the framework even before a user requests them). Others above 12 seemed to give a retain count of 1. Quoting:

From the little bit of examination I've been able to do, it looks as if you will get "shared" versions of integer NSNumbers for values in the range [0-12]. Anything larger than 12 gets you a unique instance even if the values are equal. Why twelve? No clue. I don't even know if that's a hard number or circumstantial.

Try it with 11, 12 and 13 - I think you'll find 13 is the first to give you a non-shared NSNumber.

这篇关于为什么NSNumber如此奇怪的keepCounts?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆