Created
December 17, 2014 10:19
-
-
Save dodikk/4c47b7fee92d795624e1 to your computer and use it in GitHub Desktop.
Explanation of __weak and __strong keywords
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]; | |
}; | |
} |
Not using __strong
within a callback
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)```
// weakSomeObject may be nil
[weakSomeObject someMethod]; // but not during the call
// weakSomeObject may be nil
[weakSomeObject someOtherMethod];
};
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Callback block not being executed
