如果我有:
@interface SomeClass() {
NSObject *_someObject;
}
...
- (void)someMethod {
[self doSomething:^(NSObject *someOtherObject) {
_someObject = someOtherObject;
}];
}
...
自从我们在该块中访问_someObject后,是否存在自我保留周期?
答案 0 :(得分:4)
在这种情况下,self会被保留,如果你像这里一样访问类变量,它就像:
- (void)someMethod {
[self doSomething:^(NSObject *someOtherObject) {
self->_someObject = someOtherObject;
}];
}
如果创建的块将在self之前被销毁,一切都会好的,但是如果block活得更长,那么所有其他对self的引用,self将保留在内存中,而block将不会释放它。
我建议使用这一个代码:
@interface SomeClass()
@property (nonatomic, strong)NSObject *someObject;
...
- (void)someMethod {
__weak SomeClass *weak_self = self;
[self doSomething:^(NSObject *someOtherObject) {
weak_self.someObject = someOtherObject;
}];
}
...
或
@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;
}];
}
...