【问题标题】:__weak and strong variable behaviour with blocks__weak 和 strong 变量行为与块
【发布时间】: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


【解决方案1】:

你的参考不强。只需像这样添加__strong 指令:

__strong typeof(weakSelf) strongSelf = weakSelf;

【讨论】:

  • 这不会有任何区别,因为默认情况下,对象只有在明确指定 __weak 之前才具有强类型。
  • 没关系,默认是强引用。
  • @LDNZh 我试过了,我收回我的话。你是对的。所以应用于弱引用对象的 typeof() 实际上返回 __weak Type*,而不仅仅是 Type*?
  • @NKorotkov 是的,它也很弱。
  • @LDNZh 谢谢,它确实有效。我不知道弱对象上的 typeof 会返回弱类型。
【解决方案2】:

我找到了答案。我自己真的很好奇,因为你的代码对我来说似乎是合法的。至少这个想法。所以我建立了一个类似的项目并进行了一些实验。问题是这一行:

typeof(weakSelf) strongSelf = weakSelf; 

将其更改为任一

__strong typeof(weakSelf) strongSelf = weakSelf;

按照@LDNZh 的建议或

typeof(self) strongSelf = weakSelf;

您的代码将起作用。

更新:由于这个问题经常出现,我对我的示例项目进行了一些更改。我将在github 上提供给大家以供将来参考。

【讨论】:

    猜你喜欢
    • 2015-02-03
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多