Xcode 4.2 中的retainCount 发生了什么?
我注意到,将 Xcode 更新到 4.2 后,retainCount 始终等于 -1。我在项目中没有使用 ARC,我什至尝试创建新项目并在项目设置中将 ARC 选项切换为关闭,但下一行的工作非常奇怪:
NSString *string = [[NSString alloc] init];
NSLog(@"%i", [string retainCount]); //-1
[string retain];
[string retain];
[string retain];
NSLog(@"%i", [string retainCount]); //still -1
[string release];
[string release];
[string release];
NSLog(@"%i", [string retainCount]); //still -1
我错过了什么吗?我认为如果 ARC 选项关闭,该项目将像以前一样正常工作。
I noticed that after updating my Xcode to 4.2 retainCount is always equals to -1. I don't use ARC in my project and I even tried to create new projects and switched ARC option to off in project settings but next lines works really strange:
NSString *string = [[NSString alloc] init];
NSLog(@"%i", [string retainCount]); //-1
[string retain];
[string retain];
[string retain];
NSLog(@"%i", [string retainCount]); //still -1
[string release];
[string release];
[string release];
NSLog(@"%i", [string retainCount]); //still -1
Am I miss something? I thought that if ARC option is turned off the project will work exact as before..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,让我先说一下,如果您调用
retainCount
,您可能做错了什么。这种方法应该只由编写低级框架代码的人使用,即使这样也只能在调试时使用。对象可能会在您背后保留并自动释放,因此调用-retainCount
会产生很大的误导。无论如何,我怀疑答案是
[[NSString alloc] init]
返回一个单例对象。它是不可变的,并且是空的,所以当它只能返回@""
时,它实际上没有理由为您创建一个全新的字符串。First, let me preface this by saying that if you're calling
retainCount
, you're probably doing something wrong. This method should be only used by people writing low-level framework code, and even then only when debugging. Objects may get retained and autoreleased behind your back such that calling-retainCount
is very misleading.Anyway, I suspect that the answer is that
[[NSString alloc] init]
is returning a singleton object. It's immutable, and empty, so there's really no reason why it should create a brand new string for you when it can just return@""
.