Weak references

How do you fix a retain cycle? Use a weak reference. A weak reference is a pointer that does not imply ownership. To fix our retain cycle, an asset should not own its holder. Edit Asset.h to make holder a weak reference:

#​i​m​p​o​r​t​ ​<​F​o​u​n​d​a​t​i​o​n​/​F​o​u​n​d​a​t​i​o​n​.​h​>​
@​c​l​a​s​s​ ​E​m​p​l​o​y​e​e​;​

@​i​n​t​e​r​f​a​c​e​ ​A​s​s​e​t​ ​:​ ​N​S​O​b​j​e​c​t​
{​
 ​ ​ ​ ​N​S​S​t​r​i​n​g​ ​*​l​a​b​e​l​;​
 ​ ​ ​ ​_​_​w​e​a​k​ ​E​m​p​l​o​y​e​e​ ​*​h​o​l​d​e​r​;​
 ​ ​ ​ ​u​n​s​i​g​n​e​d​ ​i​n​t​ ​r​e​s​a​l​e​V​a​l​u​e​;​
}​
@​p​r​o​p​e​r​t​y​ ​(​s​t​r​o​n​g​)​ ​N​S​S​t​r​i​n​g​ ​*​l​a​b​e​l​;​
@​p​r​o​p​e​r​t​y​ ​(​w​e​a​k​)​ ​E​m​p​l​o​y​e​e​ ​*​h​o​l​d​e​r​;​
@​p​r​o​p​e​r​t​y​ ​u​n​s​i​g​n​e​d​ ​i​n​t​ ​r​e​s​a​l​e​V​a​l​u​e​;​
@​e​n​d​

Build and run the program. Note that all the objects are now being deallocated correctly.

In a parent-child relationship, the general rule for preventing this type of retain cycle is the parent owns the child, but the child should not own the parent.

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

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