wnagrodzki / iOSProgrammingGuidelines

2 stars 0 forks source link

Extending object's lifetime #9

Closed wnagrodzki closed 5 years ago

wnagrodzki commented 6 years ago

If you are breaking reference cycle for an object bind it to a strong reference for the duration of the closure’s execution.

operation.onComplete { [weak self] result in
  guard let self = self else { return }
  let model = self.updateModel(result)
  self.updateUI(model)
}

This is to avoid deallocation of weakly referenced object during closure execution. Use strongSelf instead of self for local variable name until SR-6156 is fixed.

Related

pwetrifork commented 6 years ago

I think using recaptured weak vs capturing directly should be decided on a case-by-case basis. I imagine there can be scenarios where the captured object’s lifetime should be extended until the closure is executed.

wnagrodzki commented 6 years ago

@pwetrifork I corrected the paragraph as it was misleading and did not represent what I meant.

wnagrodzki commented 5 years ago

@pwetrifork @moskacz Does it looks good?

pwetrifork commented 5 years ago

According to the discussion at https://bugs.swift.org/browse/SR-6156, rebinding self under the same name confuses the debugger

wnagrodzki commented 5 years ago

This should be fixed in Swift 4.2: https://github.com/apple/swift-evolution/blob/master/proposals/0079-upgrade-self-from-weak-to-strong.md

pwetrifork commented 5 years ago

It looks like the change in 4.2 was only about skipping the backticks, the debugger bug is still there

wnagrodzki commented 5 years ago

@pwetrifork Yes, thanks, I added note about that issue in quotation below the code-listing.

wnagrodzki commented 5 years ago

@moskacz What is your opinion?

Moskacz commented 5 years ago

I think we should decide which variable name is preferred until bug is fixed. Seems like strongSelf is used very often by developers, so it might be right choice.

wnagrodzki commented 5 years ago

@Moskacz Ok, I updated the text.