Please kindly point out what is wrong in my code. I define a variable idleTimer of my custom type
@property (nonatomic, retain) IdleTimer *idleTimer;
Then when I run the following codes, it crashes.
IdleTimer *idleTimerTemp = [[IdleTimer alloc] initTimer:PERIOD_COUPON_POPUP];
idleTimer = idleTimerTemp;
NSLog(@"Pt. 1 %d %d", [idleTimerTemp retainCount], [idleTimer retainCount]);
[idleTimer setDelegate:self];
[idleTimerTemp release];
NSLog(@"Pt. 2 %d %d", [idleTimerTemp retainCount], [idleTimer retainCount]);
If the idleTimer is used again, it crashes.
But it I retain the idleTimerTemp on “idleTimer = idleTimerTemp”. No crash at all.
But my variable is defined as retain. what is wrong ?
Your property is defined as
retainbut that doesn’t do anything with respect to the instance variable which is the backing storage for the property. Presumably somewhere in your code, you’ve done an@synthesize idleTimer;. That creates an accessor pair which implements the memory management you requested.The only way to get that behavior is to call the accessor itself. So if you assign directly to
idleTimer, that does nothing, but if you useself.idleTimer = idleTimerTemp, then the-setIdleTimer:accessor gets called, which will retain the parameter.