Jiayu Yang
Jiayu Yang

Reputation: 111

What's the diffenence between self->_xxx and _xxx?

There is some code:

@interface Person() {
    NSString *_name1;
}
@property NSString *name2;
@property void (^blk)(void);
@end

so, What's the diffenence between self->_name1 and _name1 ? And the difference between self->_name2 and _name2 ?

    __weak __typeof__(self) weakSelf = self;
    self.blk = ^(){
    __strong __typeof(self) strongSelf = weakSelf;
        _name1 = @"123";
    }

There will be retain cycle. The solution is that change _name1 to strongSelf->_name1, But why ?

Upvotes: 0

Views: 154

Answers (1)

CRD
CRD

Reputation: 53000

If _name1 is an instance variable of a class C then in the body of an instance method of class C the simple variable reference:

_name1

is just a shorthand for:

self->_name1

and this means:

access the instance variable _name1 in the object referenced by variable self, and self is automatically set to reference the object on which the instance method was called (e.g. in [v method ...] when method is executed its self variable references the same object that the callers v referenced).

This shorthand means that accidental (not all retain cycles are unwanted or bad) retain cycles occur as uses of self are not immediately obvious.

In your code sample you have such a hidden reference to self, your use of weakSelf and strongSelf does not change the expansion of the shorthand, so:

_name1 = @"123";

still expands to:

self->_name1 = @"123";

And all your effort to avoid the retain cycle are wasted. To fix this you must not use the shorthand and instead write out what you do want:

strongSelf->_name1 = @"123";

Upvotes: 2

Related Questions