问题描述:

If I have:

@interface SomeClass() {

NSObject *_someObject;

}

...

- (void)someMethod {

[self doSomething:^(NSObject *someOtherObject) {

_someObject = someOtherObject;

}];

}

...

Will there by a retain cycle with self since we accessed _someObject within that block?

网友答案:

in this case, self will be retained, if you access to class variable like here, it the same like:

- (void)someMethod {
    [self doSomething:^(NSObject *someOtherObject) {
          self->_someObject = someOtherObject;
    }];
}

if created block will be destroyed before self, everything will be ok, but if block live longer then all other references to self, self will stay in memory, while block will not release it.

I recommend to use this one code:

@interface SomeClass()     

@property (nonatomic, strong)NSObject *someObject;

...

- (void)someMethod {
    __weak SomeClass *weak_self = self;
    [self doSomething:^(NSObject *someOtherObject) {
          weak_self.someObject = someOtherObject;
    }];
}
...

or

@interface SomeClass() {
    NSObject *_someObject;
}

...

- (void)someMethod {
    __weak SomeClass *weak_self = self;
    [self doSomething:^(NSObject *someOtherObject) {
          __strong SomeClass *strong_self = weak_self;
          strong_self->_someObject = someOtherObject;
    }];
}
...
相关阅读:
Top