Callbacks and object ownership

Inherent in any of these callback schemes is the risk of strong reference cycles. Often the object you create has a pointer to the object that is going to call back. And it has a pointer to the object you created. If they each have strong references to each other, you end up with a strong reference cycle – neither of them will ever get deallocated.

Figure 27.3  Strong reference cycle

Strong reference cycle

Thus, it was decided that:

  • Notification centers do not own their observers. If an object is an observer, it will typically remove itself from the notification center in its dealloc method:

    -​ ​(​v​o​i​d​)​d​e​a​l​l​o​c​
    {​
     ​ ​ ​ ​[​[​N​S​N​o​t​i​f​i​c​a​t​i​o​n​C​e​n​t​e​r​ ​d​e​f​a​u​l​t​C​e​n​t​e​r​]​ ​r​e​m​o​v​e​O​b​s​e​r​v​e​r​:​s​e​l​f​]​;​
    }​
    
  • Objects do not own their delegates or data sources. If you create an object that is a delegate or data source, your object should excuse itself in its dealloc method:

    -​ ​(​v​o​i​d​)​d​e​a​l​l​o​c​
    {​
     ​ ​ ​ ​[​w​i​n​d​o​w​T​h​a​t​B​o​s​s​e​s​M​e​A​r​o​u​n​d​ ​s​e​t​D​e​l​e​g​a​t​e​:​n​i​l​]​;​
     ​ ​ ​ ​[​t​a​b​l​e​V​i​e​w​T​h​a​t​B​e​g​s​F​o​r​D​a​t​a​ ​s​e​t​D​a​t​a​S​o​u​r​c​e​:​n​i​l​]​;​
    }​
    
  • Objects do not own their targets. If you create an object that is a target, your object should zero the target pointer in its dealloc method:

    -​ ​(​v​o​i​d​)​d​e​a​l​l​o​c​
    {​
     ​ ​ ​ ​[​b​u​t​t​o​n​T​h​a​t​K​e​e​p​s​S​e​n​d​i​n​g​M​e​M​e​s​s​a​g​e​s​ ​s​e​t​T​a​r​g​e​t​:​n​i​l​]​;​
    }​
    

None of these issues exist in this program because your BNRLogger object will not be deallocated before the program terminates. (Also, in a bit of a fluke, in this exercise you happen to have used two well-documented exceptions to the rules: an NSURLConnection does own its delegate while the connection is running, and an NSTimer does own its target while the timer is valid.)

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset