Narayana Narayana - 2 months ago 8
Objective-C Question

In dealloc method set any delegate to nil is needed or not needed

I have created tableview in my view by programmatic like below

table = [[UITableView alloc] initWithFrame:CGRectMake(0, 44, 320, 370) style:UITableViewCellStyleDefault];
table.delegate = self;
table.dataSource = self;
table.separatorStyle = UITableViewCellSeparatorStyleNone;
[self.view addSubview:table];


in dealloc method i write like below

table.delegate = nil;
table.dataSource = nil;
[table release];
table=nil;


this the better way or below one is better

[table release];
table=nil;


I want to know if i dont reset delegate and dataSource what will happen

Thanq

Answer

If you are deallocating an object that acts as the delegate to other objects, you need to make sure that you have set their delegates to nil, before you call [super dealloc] (assuming the normal pattern that objects do not retain their delegates). This is because when [super dealloc] has returned, this object is no longer a valid object and the objects it is a delegate to effectively have dangling references, if they have not been set to nil.

In this particular case, you would probably get away without doing it because your object's dealloc probably won't get called except when the UI is being dismantled and the table view no longer needs to use its delegate or data source, but don't bet on it.

Comments