Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we set delegate to nil at dealloc if the object is going to be destroyed anyway?

-(void) scrollViewDidScroll:(UIScrollView *)scrollView
{
    PO(NSStringFromCGPoint(self.tableView.contentOffset));
    PO(NSStringFromUIEdgeInsets(self.tableView.contentInset));

    while(false);
}

-(void)dealloc
{
    PO(NSStringFromClass([self class]));
    PO(@"Deallocated");
    self.tableView.delegate=nil;
}

Here I need to set self.tableView.delegate = nil to avoid error.

I am aware, from my previous question, that self.tableView.delegate won't automatically become nill when the delegate is destroyed. That's because the type of delegate is assign reference instead of weak reference.

However, what about self.tableView?

The only thing with strong reference to self.tableView is it's superview that's owned by self and self itsef.

So when self is destroyed, self.tableView should be destroyed too and that means self.tableView.delegate will be gone too.

So why do I need to set self.tableView.delegate=nil;

like image 396
user4951 Avatar asked Dec 18 '13 09:12

user4951


2 Answers

You need to set delegate to nil in many cases. In your case tableView can be referenced by some external class and will not destroyed after your class dealloc method. And will continue call its delegate method leading to crash. There are several classes that works in another thread (NSURLConnection for example). Even if you release it it can continue calls delegate methods since it is retained in another thread.

like image 181
Ievgenii Avatar answered Oct 11 '22 03:10

Ievgenii


If you hold the only reference to self.tableView, there's no need of setting the delegate to nil.

The only situation where you have to set the delegate to nil, if is another class has your class as a delegate, because if your class is destroyed, that other class will look for your class to implement some methods, and your call won't be there.

like image 32
Antonio MG Avatar answered Oct 11 '22 04:10

Antonio MG