Question

I have an instance of a UITableView, and a separate class that adheres to the delegate and datasource protocols. I'm doing this like so:

SubjectTableViewHandler *handler = [[[SubjectTableViewHandler alloc] init] retain];
tv.delegate = handler;
tv.dataSource = handler;
[handler autorelease];

I don't want to maintain the handler as an ivar, and if I take off the retain call at the end, when the autorelease happens, it is sent release, then added to the pool, which causes an EXC_BAD_ACCESS. So currently, the retain count is:

(1) At init: 1
(2) At retain: 2
(3) delegate/datasource properties are 'assign', still 2
(4) At autorelease: 1, now in autorelease pool.

But then since the properties are 'assign', they will never be released, the retain count will never hit 0, and the handler will never be deallocated anyway. Is there any more efficient way to accomplish this than maintaining the handler as an ivar and releasing it in the dealloc method?

Was it helpful?

Solution

When you initialize the object using init, you are claiming ownership of it and there is no reason to call retain. You also don't want to call autorelease since that will cause the object to be released at the of the run loop.

Since you need to keep the handler (so that your tableView can call the delegate/dataSource methods) and a reference to the handler after the method returns (so you can release it when you are done showing the tableView), the cleanest approach would be to make it an ivar.

OTHER TIPS

The only solution that I can see is, as you mentioned, to make it an ivar and store, allocate, and deallocate it in parallel with the table.

It all depends on your use of table view.

Common practice is you create a view controller which is a delegate to table and table may be a controller's member.

As another alternative you can inherit from UITableView and make it delegate of itself.

Sometimes it's better to use a singleton delegate.

Also, in table delegate methods first argument is tableview, so one delegate object can service multiple tables.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top