Another retain gotcha!

I created a UI object based on UIView that updates itself using a timer. So within the object initWithRect I create an NSTimer object which I retain.

-(id) initWithFrame:(CGRect)rect {
...
ticker = [[NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:@selector(tock) userInfo:nil repeats:YES] retain];
...
}

- (void) dealloc {
[ticker invalidate];
[ticker release];
}

When I have finished with the view I remove it from its super view and release it

[myview removeFromSuperView];
[myview release];

however I noticed that it’s retain count never drops to zero and is therefore never deallocated.

This is because when the timer is created and the delegate is set to self, the timer retains the delegate object.

To get around this I had to add a method to the object to cancel (invalidate) the timer so it would release the delegate object so that it’s retain count will now drop to zero. So I now do

[myview removeFromSuperView];
[myview cancelTimer];
[myview release];

And the view is now correctly deallocated.

Advertisements

About austinfrance

Technical Developer @ RedSky IT / Explorer Software
This entry was posted in Development, iPhone. Bookmark the permalink.

One Response to Another retain gotcha!

  1. austinfrance says:

    I have subsequently learned that this is called an up pointer or up link and should not be retained.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s