Search code examples
swiftretain-cycle

Does using a function as a closure retain self?


I'm having trouble tracking down a retain cycle. I think it's to do with the way I subscribe to events. Pseudo code is like this:

override func viewDidLoad() {
   func handleEvent() {
     self.doSomething()
   }

   subscribe("eventName", block: handleEvent)
}

deinit {
    unsubscribe("eventName")
} 

Will this create a retain cycle to self / my ViewController? And if so, how can I get around it? If I was using a closure, I could use [weak self], but since I'm passing a function, is there anyway to use a [weak self] equivalent?


Solution

  • Long story short, your code does retain a reference. (handleEvent->viewDidLoad->self), http://blog.xebia.com/function-references-in-swift-and-retain-cycles/ has some general strategies to avoid the issue. My recommendation would be to create a function reference, rather than declaring a function:

    let eventHandler: () -> () = { [weak self] in 
        self?.doSomething() 
    }
    subscribe("eventName", block: eventHandler)