Search code examples
objective-cmemorymemory-managementweak-references

Does a reference remain weak if passed as an argument in objective-c?


When I pass self as an argument to a function, does it make any difference if I weakify it first?

For example:

__weak __typeof(self) weakSelf = self;
[self.someObject doWorkWithDelegate: weakSelf];

In the body of the doWork function it assigns it to a strong property

@property (strong) Foo* fooDelegate;

(I know this is terrible, don't get sidetracked).

This will still be a strong reference and cause a memory cycle despite theh fact that I "weakified" the reference first, correct?

Bonus Question: How can I check this myself?


Solution

  • It is the variable weakSelf which is weak. That is, ARC does not emit a retain when a value is assigned to it, nor a release when it goes out of scope (or is assigned a different value).

    Since the fooDelegate property is strong, assigning to it releases any old value it may have had and retains the newly-assigned value.

    So, yes, that will be a strong reference. It's not clear from what you posted whether it will constitute a retain cycle. The name of the method suggests that the delegate will be cleared (thus released) after the work has been completed. In that case, it's not a problem. It would only be a problem if self.someObject maintained the strong reference until it itself was released and self maintained a strong reference to someObject until self was released.