Retain Cycle With Array Or Dictionary
The question is will it create a retain cycle if we have an array (dictionary) of objects where the object is owned elsewhere? A short answer is YES it will.
Experiments
I created a background project to test if the object in array / dictionary will create retain cycle.
Array
1 | class Retain { |
For the above code, "deist Retain" should be printed if it does not create any retain cycle. Because var retain has been reassigned, and the original Retain should call deinit to free from the memory. Result is array will create a retain cycle.
Dictionary
1 | class Retain { |
For the above code, "deist Retain" should be printed if it does not create any retain cycle. Because var retain has been reassigned, and the original Retain should call deinit to free from the memory. Result is dictionary will create a retain cycle.
Solution
You can use NSHashTable. You will need to init with NSHashTable<AnyObject>.weakObjects() . I found the solution from How to avoid a retain cycle when using an array of delegates in Swift - Stack Overflow post.’
For dictionary, use NSMapTable.
Other references:
NSHashTable & NSMapTable - NSHipster
Array
1 | class TestArraySolution() { |
Dictionary
1 | class TestDictionarySolution { |
Subscripting
The NSMapTable do not have subscripting like dictionary do. Here is how you can implement subscripting for NSMapTable using extension.
1 | extension NSMapTable { |
