Skip to content

Instantly share code, notes, and snippets.

@svd-zp
Forked from dodikk/WeakifyExplained.mm
Created March 15, 2017 13:33
Show Gist options
  • Select an option

  • Save svd-zp/07d086e26e300496ba4417e320825493 to your computer and use it in GitHub Desktop.

Select an option

Save svd-zp/07d086e26e300496ba4417e320825493 to your computer and use it in GitHub Desktop.
Explanation of __weak and __strong keywords
void foo()
{
// __strong guarantees that the object is "alive" until the end of foo() stack frame. The __strong keyword is used implicitly and may be omitted.
// Unless it's retained by other objects
__strong SomeObjectClass *someObject = ...
// __weak does not let the block increase the retain count of "someObject"
//
__weak SomeObjectClass *weakSomeObject = someObject;
someObject.completionHandler = ^void(void){ // default signature is ``` ^id(void)```
// Ensure that someObject won't be deallocated until the end of the someObject.completionHandler() stack frame
// SomeObject becomes retained only when the block is invoked. And it becomes released after the return statement within the someObject.completionHandler()
SomeObjectClass *strongSomeObject = weakSomeObject;
// "if" statement is not that useful since invoking a selector on a nil objects results to IDLE (no action).
if (strongSomeObject == nil) {
// The original someObject doesn't exist anymore.
// Ignore, notify or otherwise handle this case.
}
// okay, NOW we can do something with someObject
[strongSomeObject someMethod];
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment