Skip to content

Instantly share code, notes, and snippets.

@dodikk
Created December 17, 2014 10:19
Show Gist options
  • Save dodikk/4c47b7fee92d795624e1 to your computer and use it in GitHub Desktop.
Save dodikk/4c47b7fee92d795624e1 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];
};
}
@dodikk
Copy link
Author

dodikk commented Dec 18, 2014

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];
  };
}

Callback Inactive

Weak reference during the call

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