保留计数 NSArray 与 NSMutableArray
带有代码示例的简短问题:
NSLog(@"%i", [[[NSArray alloc] init] retainCount]);
NSLog(@"%i", [[[NSMutableArray alloc] init] retainCount]);
输出:
2
1
为什么 NSArray 和 NSMutableArray 的保留计数不同?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
苹果之外没有人确切知道(但我确信很快就会有人声称他确切知道为什么会发生这种情况)。
也许发生这种情况是因为 iOS 很聪明,它重用了空的 NSArray。显然
[[NSArray alloc] init]
创建了一个没有实际用途的空数组。而且由于它是不可变的(即以后不能添加对象,并且它将永远为空),因此所有空 NSArrays 指针都可以引用同一个对象。可变的不能重复使用,因为您可以向其中添加对象。
不要使用retainCount!
来自 苹果文档:
Nobody outside of apple knows for sure (but I'm sure soon there will be somebody that claims he knows exactly why that happened).
Maybe this happens because iOS is smart and it reuses empty NSArrays. And obviously
[[NSArray alloc] init]
creates an empty array that is of no real use. And since it`s not mutable (ie you can't add objects later, and it will be empty forever) all empty NSArrays pointers can reference the same object.The mutable one can't be reused because you can add objects to it.
Do not use retainCount!
From the apple documentation:
原因是 [[NSArray alloc] init] 无论调用多少次都会返回相同的对象。看一下这段代码:
输出是:
这是有道理的,因为 NSArray 是不可变的,并且所有空数组都是相同的。看起来 NSArray 为此目的保留了一个空数组,因为 array1、array2 和 array3 指向的数组的保留计数是 4。
我不同意 @fluchtpunkt 的答案,但我认为可以肯定地说,我们确切地知道为什么会发生这种情况。我想你可能会说没有人确切知道为什么苹果选择以这种方式实现它,但这看起来确实是一个好主意。
The reason is that [[NSArray alloc] init] returns the same object no matter how many times you call it. Look at this code:
The output is:
This makes sense, because NSArray is immutable, and all empty arrays are identical. It looks like NSArray keeps an empty array handy for this purpose since the retain count for the array pointed to by array1, array2, and array3 is 4.
I don't disagree with @fluchtpunkt's answer, but I think it's safe to say that we know exactly why this happens. I suppose you could say that nobody knows exactly why Apple chose to implement it this way, but it does seem like a good idea.