Skip to content

Instantly share code, notes, and snippets.

@jspahrsummers
Last active December 16, 2015 20:09
Show Gist options
  • Save jspahrsummers/5490301 to your computer and use it in GitHub Desktop.
Save jspahrsummers/5490301 to your computer and use it in GitHub Desktop.
Demonstrating the semantics of __weak objects in Objective-C. See http://clang.llvm.org/docs/AutomaticReferenceCounting.html#semantics for more information.
// The weak pointer is read, and retained until the message send completes its synchronous work.
[weakValue doAThing];
- (void)doAThing {
// Within here, 'self' is __strong.
__unsafe_unretained selfCopy = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// 'selfCopy' may be garbage here.
[selfCopy doAnotherThing];
});
}
@JaviSoto
Copy link

Second one is obviously bad, but what about this:

__weak selfCopy = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [selfCopy doAnotherThing];

        // selfCopy may point to nil here, never to garbage, right?
        [selfCopy doSomethingElse];
    });

@jspahrsummers
Copy link
Author

@JaviSoto Yep, your comment is correct.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment