以下代码工作正常,您可以在系统上运行它以进行确认。
我的问题是,如您所见,仅当保留计数达到零时才调用 dealloc 方法,这意味着为 RetainTracker 对象释放了内存。但是,问题是当我在 dealloc 方法中记录保留计数时,它仍然显示保留计数为 1。这是为什么呢?
这是我的代码:
#import <Foundation/Foundation.h>
@interface RetainTracker : NSObject
@end
@implementation RetainTracker
- (id)init {
if (self = [super init]) {
NSLog(@"init: Retain count of %lu",(unsigned long)[self retainCount]);
}
return self;
}
- (void)dealloc {
NSLog(@"Dealloc called bye bye!==>%lu",(unsigned long)self.retainCount);
[super dealloc];
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
RetainTracker *myRetainTracker = [RetainTracker new];
[myRetainTracker retain]; // count-->2
NSLog(@"The retain count is ==>%lu",(unsigned long)myRetainTracker.retainCount);
[myRetainTracker release];// count -->1
NSLog(@"The retain count is ==>%lu",(unsigned long)myRetainTracker.retainCount);
[myRetainTracker retain];// count -->2
NSLog(@"The retain count is ==>%lu",(unsigned long)myRetainTracker.retainCount);
[myRetainTracker release];// count -->1
NSLog(@"The retain count is ==>%lu",(unsigned long)myRetainTracker.retainCount);
[myRetainTracker release];// count -->0
NSLog(@"The retain count is ==>%lu",(unsigned long)myRetainTracker.retainCount);
}
return 0;
}
以下是日志:
init: Retain count of 1
The retain count is ==>2
The retain count is ==>1
The retain count is ==>2
The retain count is ==>1
Dealloc called bye bye!==>1
The retain count is ==>1