| Start |
|---|
| Reference Cycles and Weak References A reference cycle (or retain cycle) is so named because it indicates a cycle (opens new window) in the object graph (opens new window): Each arrow indicates one object retaining (opens new window) another (a strong reference). Unless the cycle is broken, the memory for these objects will never be freed. A retain cycle is created when two instances of classes reference each other: Both instances they will live on until the program terminates. This is a retain cycle. Weak ReferencesTo avoid retain cycles, use the keyword Weak or unowned references will not increase the reference count of an instance. These references don't contribute to retain cycles. The weak reference becomes When working with closures, you can also use |
| Manual Memory Management When interfacing with C APIs, one might want to back off Swift reference counter. Doing so is achieved with unmanaged objects. If you need to supply a type-punned pointer to a C function, use Note that, if using To interact with legacy Objective-C APIs, one might want to manually affect reference count of a certain object. For that These solutions should always be the last resort, and language-native APIs sould always be preferred. RemarksWhen to use the weak-keyword:Theweak-keyword should be used, if a referenced object may be deallocated during the lifetime of the object holding the reference. When to use the unowned-keyword:Theunowned-keyword should be used, if a referenced object is not expected to be deallocated during the lifetime of the object holding the reference. PitfallsA frequent error is to forget to create references to objects, which are required to live on after a function ends, like location managers, motion managers, etc.Example: This example will not work properly, as the location manager is deallocated after the initializer returns. The proper solution is to create a strong reference as an instance variable: |
Read Article
https://develop.horje.com/learn/1434/reference