0

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 ?

SkyEagle888
  • 1,009
  • 2
  • 18
  • 42

2 Answers2

2

You're assigning to the idleTimer ivar directly instead of using the accessors. Do this instead:

self.idleTimer = idleTimerTemp;

The property accessors can't implement the semantics you specify if you don't use them.

Caleb
  • 124,013
  • 19
  • 183
  • 272
2

Your property is defined as retain but 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 use self.idleTimer = idleTimerTemp, then the -setIdleTimer: accessor gets called, which will retain the parameter.

Chris Parker
  • 1,252
  • 8
  • 7