开发者

Releasing objects: [obj release]; is not enough, need [obj release], obj = nil;?

开发者 https://www.devze.com 2023-04-03 10:39 出处:网络
Here I got some ugly code: NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@\"yyyy\"];

Here I got some ugly code:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy"];
NSDate *date = [NSDa开发者_开发技巧te 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] ?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消