Xcode 4.2 中的retainCount 发生了什么?

发布于 2024-12-13 11:57:44 字数 469 浏览 3 评论 0原文

我注意到,将 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梨涡少年 2024-12-20 11:57:44

首先,让我先说一下,如果您调用 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 @"".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文