为什么 NSNumber 有这么奇怪的 retainCounts? [英] Why has NSNumber such strange retainCounts?

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

问题描述

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

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

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.

我发现了一个奇怪的情况.实际上,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

推荐答案

基于此链接 此处,可能对常见的 NSNumber 进行了一些优化(这可能不会在所有实现中发生,因此可能是 @dizy 的 retainCount 为 1 的原因).

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).

基本上,因为 NSNumbers 是非可变的,底层代码可以自由地为您提供相同数字的第二个副本,这将解释为什么保留计数为 2.

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.

n和n1的地址是什么?我怀疑它们是一样的.

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);

根据您的更新,我给您的链接几乎肯定是问题所在.有人进行了测试,发现从 0 到 12 的 NSNumber 将为您提供已创建的副本(它们实际上可能在用户请求之前由框架创建).其他超过 12 的似乎保留计数为 1.引用:

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:

从我能够做的一点点检查来看,似乎您将获得 [0-12] 范围内值的整数 NSNumbers 的共享"版本.即使值相等,任何大于 12 的值都会为您提供一个唯一的实例.为什么是十二?没有线索.我什至不知道这是一个硬性数字还是间接数据.

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.

试试 11、12 和 13 - 我想你会发现 13 是第一个给你一个非共享 NSNumber 的.

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

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

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