Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Mascots

macrumors 68000
Sep 5, 2009
1,667
1,418
unowned is for when that reference will continue to exist through the times that your closure can get called. I've found that in most cases, the user can just navigate back out, and so that reference can't be guaranteed, unless for example viewWillDisappear cleans it up, so weak is generally more appropriate.

And when they are useful: sometimes you'll have blocks associated with objects that should only be called during the lifetime of said object. That'd be an instance to use unowned, since you'd generally want that guarantee in a scenario like that and a crash-exit on improper memory access can be preferred over being thrown into a invalid or unpredictable state.
 
  • Like
Reactions: MarkCollette

mildocjr

macrumors 65816
Original poster
unowned is for when that reference will continue to exist through the times that your closure can get called. I've found that in most cases, the user can just navigate back out, and so that reference can't be guaranteed, unless for example viewWillDisappear cleans it up, so weak is generally more appropriate.

Tracking like a train now, thanks for the post.
 

1458279

Suspended
May 1, 2010
1,601
1,521
California
Just wondering what the ObjC version of this would be. I know "__block" allows a var to retain any value it gets during the exec of the block, but this sounds different.

It sounds like not only a var that could be assigned outside the block, but a var that can live after the block dies.

Actually, doesn't the __block do that?
 

Mascots

macrumors 68000
Sep 5, 2009
1,667
1,418
Remembered this and grabbed it from Da Apple Docs (Swift w/ Cocoa & Objc):

“Swift closures and Objective-C blocks are compatible, so you can pass Swift closures to Objective-C methods that expect blocks. Swift closures and functions have the same type, so you can even pass the name of a Swift function.

Closures have similar capture semantics as blocks but differ in one key way: Variables are mutable rather than copied. In other words, the behavior of __block in Objective-C is the default behavior for variables in Swift.”
 

1458279

Suspended
May 1, 2010
1,601
1,521
California
Remembered this and grabbed it from Da Apple Docs (Swift w/ Cocoa & Objc):
Ok wait. if __block is the default behavior in Swift, what about when you don't want that behavior? The standard behavior of ObjC is now the non-standard behavior in Swift?

I can't say that I have a case point in mind, but reversing the standard behavior has to have a case where it causes problems. Moreover, this would be a slippery bug to chase down.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.