释放对象:[objrelease];还不够,需要[obj release], obj = nil;?

发布于 2024-12-03 13:07:51 字数 727 浏览 1 评论 0原文

这里我得到了一些丑陋的代码:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy"];
NSDate *date = [NSDate date];
NSString *textWithYear = [NSString stringWithFormat:@"text and year %@", [dateFormatter stringFromDate:date] ];
[dateFormatter release];
NSLog(@"%i", [dateFormatter retainCount]); // returns 1 !

如你所见,retains counter 返回 1,我想这意味着该对象没有被释放。 如果我将该字符串更改为

[dateFormatter release], dateFromatter = nil;

保留计数器返回 0,这可能是因为它无法计算 nil 的保留:)

是否有一些我不理解保留计数器的内容,或者该对象确实没有被释放?当我第二次向它发送 release 时(努力获得零保留计数),它会按预期崩溃:)

还有一个问题:如果 dateFormatter 真的被释放了,为什么当我释放它时它不会崩溃调用 [dateFormatter keepCount] ?

Here I got some ugly code:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy"];
NSDate *date = [NSDate date];
NSString *textWithYear = [NSString stringWithFormat:@"text and year %@", [dateFormatter stringFromDate:date] ];
[dateFormatter release];
NSLog(@"%i", [dateFormatter retainCount]); // returns 1 !

As you see, retains counter returns 1, which I suppose means that the object is not released.
If I change that string to

[dateFormatter release], dateFromatter = nil;

retains counter returns 0, which is supposedly because it can't count retains for nil :)

Is there something that I don't understand about retains counter, or this object is really not released? When I send release to it for the second time (striving to get zero retains count) it crushes expectedly :)

And one more question: if the dateFormatter was really released, why doesn't it crash when i call [dateFormatter retainCount] ?

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

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

发布评论

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

评论(1

起风了 2024-12-10 13:07:51

您正在正确释放您的对象;不用担心保留计数。并且不要使用-retainCount。请参阅何时使用 -retainCount?调用 -retainCount 被认为有害 了解有关原因的更多详细信息。

请注意,如果对象确实被销毁,这里的代码将会崩溃(因为对 -retainCount 的调用是在您释放它之后进行的,并且可能是对悬空指针的调用);使用完变量后将变量设置为nil是防止这种情况发生的好习惯。但这与你的代码是否泄漏无关。

You are correctly releasing your object; don't worry about the retain count. And don't use -retainCount. See When to use -retainCount? or Calling -retainCount Considered Harmful for more details about why.

Do note that your code here will crash if the object does get destroyed (because the call to -retainCount comes after you've released it and may be to a dangling pointer); setting your variables to nil after you are done with them is a good habit to protect against this. But it has nothing to do with whether your code is leaking.

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