The below code works fine, you can run it at your system for confirmation.
My question is, as you can see, the dealloc method is only called when the retain count reaches zero, meaning the memory is freed for the RetainTracker object. However, the issue is when I log the retain count in dealloc method, it still shows a retain count of 1. Why is this?
Here is my code:
#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;
}
Here are the logs:
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