In Objective C you can define a property as having a strong or weak reference like so:
@property(strong)... @property(weak)...
How is this done in swift?
A weak reference is just a pointer to an object that doesn't protect the object from being deallocated by ARC. While strong references increase the retain count of an object by 1, weak references do not. In addition, weak references zero out the pointer to your object when it successfully deallocates.
Weak References. A weak reference is a reference that doesn't keep a strong hold on the instance it refers to, and so doesn't stop ARC from disposing of the referenced instance. This behavior prevents the reference from becoming part of a strong reference cycle.
If you have a strong reference to an object, then the object can never be collected/reclaimed by GC (Garbage Collector). If you only have weak references to an object (with no strong references), then the object will be reclaimed by GC in the very next GC cycle.
strong is the default. An object remains “alive” as long as there is a strong pointer to it. weak specifies a reference that does not keep the referenced object alive. A weak reference is set to nil when there are no strong references to the object.
Straight from the Swift Language guide:
class Person { let name: String init(name: String) { self.name = name } var apartment: Apartment? deinit { println("\(name) is being deinitialized") } } class Apartment { let number: Int init(number: Int) { self.number = number } weak var tenant: Person? deinit { println("Apartment #\(number) is being deinitialized") } }
properties are strong by default. But look at the tenant property of the class "Apartment", it is declared as weak. You can also use the unowned keyword, which translates to unsafe_unretained from Objective-C
https://itunes.apple.com/tr/book/swift-programming-language/id881256329?mt=11
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With