当前位置: 动力学知识库 > 问答 > 编程问答 >

ios - Accessing instance variable causing retain cycle?

问题描述:

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;
    }];
}
...
分享给朋友:
您可能感兴趣的文章:
随机阅读: