释放对象:[objrelease];还不够,需要[obj release], obj = nil;?
这里我得到了一些丑陋的代码:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在正确释放您的对象;不用担心保留计数。并且不要使用
-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 tonil
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.