Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Am I responsible for releasing a UIView's gestureRecognizers in dealloc?

I have attached a UIGestureRecognizer to a UIView. Whose responsibility is it to release this during dealloc?

Specifically:

UITapGestureRecognizer *t = 
[[UITapGestureRecognizer alloc] initWithTarget:self.view action:@selector(tapHandler:)];

[self.view addGestureRecognizer:t];
[t release];

So, self.view currently has sole retention of the gestureRecognizer.

Update I should have been clearer. My question has to do with the views dealloc method. Does the view's superclass handle release of the gestureRecognizer when the view is released. I currently assume that is the case.

like image 301
dugla Avatar asked Feb 04 '11 16:02

dugla


2 Answers

The rule of thumb is that you call release whenever you call alloc, new or copy.

Since you called alloc, your code is not over-releasing or leaking anything.

While you could autorelease your gesture recognizer, I would not because explicitly releasing objects, where possible, is better memory management. (Autoreleased objects don't get released until the autorelease pool is drained.)

like image 126
Moshe Avatar answered Oct 05 '22 17:10

Moshe


Your code is correct.

The view takes ownership of the gesture recoginzer with [self.view addGestureRecognizer:t].

You could tidy your code by autoreleasing t when you create it:

UITapGestureRecognizer *t = [[[UITapGestureRecognizer alloc] initWithTarget:self.view action:@selector(tapHandler:)] autorelease];
[self.view addGestureRecognizer:t];

This would mean that all ownership of t is handled in one place thus reducing the potential for introducing problems if the code gets modifed.

like image 27
Benedict Cohen Avatar answered Oct 05 '22 16:10

Benedict Cohen