akaru
akaru

Reputation: 6317

Autorelease and selectors

I'm confused as to whether or not using UIView addTarget:action: causes that view to be retained. Specifically, I have a UITableView with custom cell views which are registered with an event on a view controller. These cell views are autoreleased.

UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

UIView *cellView = [[UIView alloc] initWithFrame:viewRect];


[cellView addTarget:self action:@selector(dosSomething:) forControlEvents:UIControlEventTouchUpInside]; //is this not a good idea?

[cellView autorelease]; //will this get released?
}

Upvotes: 0

Views: 198

Answers (2)

Rajender Kumar
Rajender Kumar

Reputation: 1377

you can release cellView here. there's no problem in releasing cellView and it will not leads to any crash. But make sure you are not using this view later in the function and add cellView to your cell's content view before releasing the cellView.

UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

UIView *cellView = [[UIView alloc] initWithFrame:viewRect];


[cellView addTarget:self action:@selector(dosSomething:) forControlEvents:UIControlEventTouchUpInside]; //is this not a good idea?

[cell.contentView addSubView:cellView];

[cellView release]; //will this get released?
}

This will work perfectly.

Upvotes: 0

BoltClock
BoltClock

Reputation: 724452

addTarget:action:forControlEvent: does not affect a view's retain count in any way. The way you call autorelease now is fine; your view will be placed in the autorelease pool and eventually released.

Note that for your view to be useful you have to add it as a subview to some other view (e.g. your cell). That view will retain it there because it will take ownership of your view, but by calling autorelease here you are handling things correctly.

Upvotes: 1

Related Questions