Swift NSBlockOperation()泄漏:无法使NSBlockOperation()变弱 [英] Swift NSBlockOperation() Leak: cannot make NSBlockOperation() weak

查看:103
本文介绍了Swift NSBlockOperation()泄漏:无法使NSBlockOperation()变弱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了避免在Objective-C中使用NSBlockOperation时发生内存泄漏,我们必须将变量声明为弱变量,以便能够引用块内的块操作(如果需要可以取消),通常是这样的:

To avoid a memory leak when using NSBlockOperation in Objective-C, we would have to declare the variable as weak to be able to reference the block operation inside the block (to cancel if needed), typically like this:

__weak NSBlockOperation *blockOp  = [NSBlockOperation blockOperationWithBlock:^{
     if (blockOp.cancelled) {
         ...
     }
}];

但是在Swift中,当我尝试将我的NSBlockOpeartion声明为弱时,它始终为nil.

But in Swift, when I try declare my NSBlockOpeartion as weak, it is always nil.

weak var blockOp = NSBlockOperation()

没有弱引用,一切都很好,除了每次都会泄漏一点内存.如何在不泄漏Swift内存的情况下引用块内的块?

Without the weak reference, all is fine except it is leaking a little bit of memory each time. How can I reference the block inside the block without leaking memory in Swift?

推荐答案

您可以使用显式的捕获列表来捕获对该操作的无用引用. (这是我实际上建议使用无主引用的唯一几次,因为该操作将在执行其块时一直保留.如果您对此保证仍然不满意,则可以改用weak.)

You can use an explicit capture list to capture an unowned reference to the operation. (This is one of the only times I'd actually suggest using unowned references, since the operation will be retained as long as its block is executing. If you're still uncomfortable with that guarantee, you could use weak instead.)

let op = NSBlockOperation()
op.addExecutionBlock { [unowned op] in
    print("hi")
    if op.cancelled { ... }
}

请注意,由于不能从其自身的初始值引用该变量,因此必须将其分为两行.

Note that this has to be split into two lines, because the variable can't be referenced from its own initial value.

这篇关于Swift NSBlockOperation()泄漏:无法使NSBlockOperation()变弱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆