【发布时间】:2015-09-24 19:32:20
【问题描述】:
我是块的新手,在通过互联网阅读时,我发现我必须使用弱变量来块,因为块保留了变量。在将 self 与块一起使用时,我有点困惑。举个例子:
@interface ViewController : UIViewController
@property (copy, nonatomic) void (^cyclicSelf1)();
-(IBAction)refferingSelf:(id)sender;
-(void)doSomethingLarge;
@end
这里我有一个 ViewController,它声明了带有 copy 属性的 block 属性。我不想进行保留循环,所以我知道在块中使用 self 时我需要创建 self 的弱对象,例如:
__weak typeof(self) weakSelf = self;
我要确保我的块在后台线程上执行,并且可能在它完成之前被用户回击。我的街区正在执行一些有价值的任务,我不希望它松动。所以我需要 self 直到块结束。我在我的实现文件中做了以下操作:
-(IBAction)refferingSelf:(id)sender
{
__weak typeof(self) weakSelf = self; // Weak reference of block
self.cyclicSelf1 = ^{
//Strong reference to weak self to keep it till the end of block
typeof(weakSelf) strongSelf = weakSelf;
if(strongSelf){
[strongSelf longRunningTask];//This takes about 8-10 seconds, Mean while I pop the view controller
}
[strongSelf executeSomeThingElse]; //strongSelf get nil here
};
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), self.cyclicSelf1);
}
据我说,使用typeof(weakSelf) strongSelf = weakSelf; 应该会创建一个对我的self 的强引用,当用户回击时,self 在块内仍然会有一个强引用,直到范围结束。
请帮助我理解为什么会崩溃?为什么我的 strongSelf 没有握住物体。
【问题讨论】:
-
你遇到了什么错误?
-
@NKorotkov strongSelf 为 nil,并且该块无法 `[strongSelf executeSomeThingElse]`。 strongSelf 是块内 self 的强指针,在块结束之前它不应该为零。如果我错了,请告诉我。
标签: ios objective-c memory-management automatic-ref-counting objective-c-blocks