Reputation: 154
In case when there are many references to weakSelf inside block, it is recommended to create its strong version. The code looks like this:
__weak typeof(self) weakSelf = self;
self.theBlock = ^{
__strong typeof(self) strongSelf = weakSelf;
[strongSelf doSomething];
[strongSelf doSomethingElse];
};
What I am concerned with is this line in the above code:
__strong typeof(self) strongSelf = weakSelf;
Isn't it erroneous when we write typeof(self)
? Is referencing self
allowed here?
In the tutorials they sometimes write:
__strong typeof(weakSelf) strongSelf = weakSelf;
Both versions are used 50/50. Are the both correct?
Upvotes: 2
Views: 656
Reputation: 53000
Isn't it erroneous when we write typeof(self)? Is referencing self allowed here?
(A) No. (B) yes
typeof
is an (Objective-)C language extension which in a declaration (here you are declaring strongSelf
) is handled by the compiler as compile time - there is no use of typeof
in the resulting compiled code. A primary use of typeof
is in #define
macros which enables a single macro to be expanded to work on different types; again such macro expansion occurs at compile time.
In your case you are constructing a block in an instance method, in abstract your code will look something like:
@implementation SomeClass {
- (someReturnType) someInstanceMethod {
... ^{ typeof(self) strongSelf = weakself; ... } ...
} }
Here typeof(self)
is effectively just a "shorthand" for SomeClass
. The use of self
is processed at compile time and no reference to runtime object referenced by self
is captured.
Both versions are used 50/50. Are the both correct?
The are identical in meaning. The rules of ARC state that if no qualifier is present then __strong
is assumed, so one version relies on this and the other makes the qualifier explicit.
HTH
Upvotes: 2