为什么retainCount返回-1

发布于 2025-01-04 22:23:00 字数 564 浏览 0 评论 0原文

据我所知,如果一个对象的保留计数变为0,它的dealloc就会被调用。但是我得到的保留计数为-1。这是什么意思?

我正在使用以下代码 -

    Demo *obj1 = [[Demo alloc] init];
    NSString *s = [[NSString alloc] initWithString:@"mithilesh"];
    NSString *s1 = [NSString stringWithString:s];
    [s release];
    object_setInstanceVariable(obj1, [propertyName cString], s1);
    //printing retain count 
    NSLog(@"retain count of name = %i",[obj1.name retainCount]);

输出:

   retain count of name = -1

释放时方法 stringWithString: 返回的字符串?

As i know, If retain count of a object goes to 0 its dealloc gets called.But i am getting retain count as -1. What does it mean?

I am using following code-

    Demo *obj1 = [[Demo alloc] init];
    NSString *s = [[NSString alloc] initWithString:@"mithilesh"];
    NSString *s1 = [NSString stringWithString:s];
    [s release];
    object_setInstanceVariable(obj1, [propertyName cString], s1);
    //printing retain count 
    NSLog(@"retain count of name = %i",[obj1.name retainCount]);

Output :

   retain count of name = -1

String returned by method stringWithString: when get release ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

迷乱花海 2025-01-11 22:23:00

这意味着您需要停止调用 -retainCount。它纯粹是一个调试功能,除非您是一位从事系统框架或编译器工作的苹果工程师,否则您可能没有任何必要查看该功能。

也就是说,您在这里看到的 INT_MAX 被解释为带符号的数字。听起来您已经掌握了一个常量字符串,可能是 @"mithillesh"。常量字符串是不参与 -retain-release 的单例,并且 -retainCountINT_MAX就是一个迹象。但这实际上只是猜测,您应该停止查看 -retainCount

如果您不相信我,也许您会相信 Bill Bumgarner 说的retainCount 没用

It means you need to stop calling -retainCount. It's purely a debugging function, and unless you're an Apple engineer working on system frameworks or the compiler, you probably have no business whatsoever looking at that function.

That said, what you're seeing here is INT_MAX being interpreted as a signed number. It sounds like you've got ahold of a constant string, likely @"mithilesh". Constant strings are singletons that don't participate in -retain and -release, and a -retainCount of INT_MAX is an indication of this. But this is really just speculation, and you should stop looking at -retainCount.

If you don't believe me, maybe you'll believe Bill Bumgarner when he says retainCount is useless.

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