Search code examples
swiftclosuresself

Is a getter over a property saving self from capturing inside block


For example I have the following controller:

class MyController : UIViewController
{
    var capturedProperty : Property?

    func getterForCapturedProperty() -> Property?
    {
        return capturedProperty
    }

    func viewDidAppear()
    {
        NetworkOperationBlock{
            someResult -> Void in

            self.getterForCapturedProperty().result = someResult
        } 
    }
}

Now even though I suppose that making a getter over the property should not influence whether self is captured or not, but still I'm not sure.

Can somebody make a quick explanation on this example?


Solution

  • No, this does not affect capturing.

    If you don't want the block to have a strong reference to self, you should mark it unowned:

    let myBlock: /* type */ = { [unowned self] in
        // ...
    }
    

    More info: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html (scroll down to "Resolving Strong Reference Cycles for Closures").