2
votes

I have the following Swift code:

  func callback(_ status: PHAuthorizationStatus) {

  }

  func myFunction() {

    let handler:(PHAuthorizationStatus) -> Void = { (status) in
         self.callback(status)
     }

      PHPhotoLibrary.requestAuthorization(for: .addOnly) { (status) in
          handler(status)
     }       

  }

What my doubt is whether there is a retain cycle in closures declared as local variable and whether we should use unowned or weak self instead inside handler. How does Swift handle closures declared as local var inside function?

1
You should see for yourself in the memory graph debugger. This is a good learning opportunity. It looks like the chain of retains here will be PHPhotoLibrary -> handler -> self. self doesn't retain PHPhotoLibrary, so there shouldn't be an issue. And besides, PHPhotoLibrary is only likely to retain hanlder until it inevitably calls it, so even if there was a retain cycle, it looks like it'll be temporary and will go away on its own once requestAuthorization finishes its job. But to be sure, you would have to inspect this in the memory debugger and InstrumentsAlexander

1 Answers

2
votes

There are two possibilities: Either the function that you call can only call the closure while the function itself is running, then the local variable keeps the closure alive.

Or the function that you call will save the closure away somewhere, and the closure may be called after the function has returned. In that case, the function will declare its closure parameter as "@escaping" and that will keep it alive.