简体   繁体   English

为什么 self 不会在块中自动声明为无主?

[英]Why isn't self automatically declared as unowned in blocks?

Up till now, I've been naïvely using Swift without really caring about the memory management.到目前为止,我一直很天真地使用 Swift 而没有真正关心内存管理。 But I'm implementing a capture list, and I guess it sort of makes sense.但我正在实施一个捕获列表,我想这有点道理。

My question is - why wouldn't self be automatically made unowned to avoid retain cycles?我的问题是 - 为什么不自动将self设为无主以避免保留周期? Is there a situation in which you'd explicitly need self to be owned that couldn't be resolved by saving some of its data elsewhere?是否存在您明确需要拥有self而无法通过将其某些数据保存在其他地方来解决的情况?

Give you a simple example给你一个简单的例子

This is a class that I need to use self,not unowned self这是一个我需要使用 self 而不是unowned self

If I use self here如果我在这里使用self

class Test{

func log(){
    println("log");
}
func FunctionHaveBlock(){
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
        () -> Void in

        sleep(4)
        self.log()
    })
}
deinit{
    println("Deinit")
}
}

Then call然后打电话

  var test:Test? = Test()
    test!.FunctionHaveBlock();
    test = nil;

The code will executed well,after 4 seconds,it will log代码会执行得很好,4秒后,它会记录

log Deinit登录取消初始化

But if I changed to unowned self ,但如果我改成unowned self

class Test{

func log(){
    println("log");
}
func FunctionHaveBlock(){
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
        [unowned self]
        () -> Void in

        sleep(4)
        self.log()
    })
}
deinit{
    println("Deinit")
}

} }

Then call然后打电话

   var test:Test? = Test()
    test!.FunctionHaveBlock();
    test = nil;

It will log它会记录

Deinit初始化

then After 4 seconds,the app crashed.Because,the object is dealloced.然后在 4 秒后,应用程序崩溃了。因为,对象被释放了。

So,if you need to retain the object,you do not use unowned self所以,如果你需要保留对象,你不要使用unowned self

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM