views:

1373

answers:

3

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?

+1  A: 

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.

cobbal
I wonder why this is downvoted to -2? Storing a reference to the datasource in an instance variable somewhere *is* the right thing to do.
Mark Bessey
I can't undownvote, but Mark is correct. I may have misread originally, but just for the record, I have mistakenly downvoted this answer. (sorry)
Kailoa Kadano
+5  A: 

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.

Martin Gordon
Agree here. Don't fight the framework. Is there a specific reason you don't want to use an ivar?
Kailoa Kadano
It didn't make sense conceptually to have an ivar, since there is no use for the variable outside the method that sets the handler. The perfect solution would be if the datasource/delegate properties were 'retain'. Then they could be set, and released, and the class that sets them wouldn't need to worry about it anymore.
craig
I think the reason it's set to assign is so that you don't create a retain cycle. You often create the object that takes a delegate from the object that becomes the delegate. In that case, you wouldn't want that object retaining it's delegate and it's delegate retaining the object.
Martin Gordon