下面我得到了一些难看的代码:
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 !如你所见,保留计数器返回1,我认为这意味着对象没有被释放。如果我将字符串更改为
[dateFormatter release], dateFromatter = nil;保留计数器返回0,这可能是因为它不能计数保留为nil :)
有没有什么我不理解的关于保留计数器的东西,或者这个对象真的没有被释放?当我第二次向它发送release (努力获得0保留计数)时,它意外地崩溃了:)
还有一个问题:如果dateFormatter真的发布了,为什么当我调用dateFormatter retainCount时它不会崩溃?
发布于 2011-09-09 05:36:58
您正确地释放了对象;不用担心保留计数。并且不要使用-retainCount。有关原因的更多详细信息,请参阅When to use -retainCount?或Calling -retainCount Considered Harmful。
请注意,如果对象确实被销毁了,这里的代码将崩溃(因为对-retainCount的调用是在您释放它之后发生的,并且可能是指向一个悬空指针);在使用完变量之后将它们设置为nil是防止这种情况发生的一个好习惯。但这与你的代码是否泄漏没有关系。
https://stackoverflow.com/questions/7354771
复制相似问题