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

后端 未结 4 1108
死守一世寂寞
死守一世寂寞 2021-02-15 17:18
-(void) scrollViewDidScroll:(UIScrollView *)scrollView
{
    PO(NSStringFromCGPoint(self.tableView.contentOffset));
    PO(NSStringFromUIEdgeInsets(self.tableView.conten         


        
相关标签:
4条回答
  • 2021-02-15 17:23

    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.

    0 讨论(0)
  • 2021-02-15 17:25

    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.

    0 讨论(0)
  • 2021-02-15 17:39

    Lets say we have a SpriteKit scene where you have a gesture recognizer and you set its delegate.

    Then you dealloc this scene and its recognizer from its controller.

    It would lead to crash if the delegate method was called in scene during this process.

    0 讨论(0)
  • 2021-02-15 17:47

    Actually this is not required. We are doing this to avoid forming retain cycle. We should not create a delegate with strong reference. If you accidentally created a delegate with strong reference then both parent and child will not get released. In that case dealloc itself will not get called. So it s not necessary.

    0 讨论(0)
提交回复
热议问题