简体   繁体   中英

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. 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? 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?

Give you a simple example

This is a class that I need to use self,not unowned self

If I use self here

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

log Deinit

But if I changed to 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.

So,if you need to retain the object,you do not use unowned self

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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