在Swift 4,Xcode版本10.1(10B61)中委派保留周期

时间:2019-01-01 13:31:34

标签: ios swift delegates automatic-ref-counting

import UIKit
import Foundation

protocol SendDataDelegate: class { }

class SendingVC {
   weak var delegate:SendDataDelegate?

   init() {
     print("Sender Init")
   }
   deinit {
      print("Dealocate SenderVC")
   }
}

class RecevingVC: SendDataDelegate {
     lazy var sendingVC: SendingVC = {
     let vc = SendingVC()
        vc.delegate = self
        print("delegate init")
        return vc
}()
    init() {
       print("Receving init")
    }
    deinit {
       print("Dealocate Receiving")
    }
}

var recevingOb: RecevingVC? = RecevingVC()
//print(recevingOb!.sendingVC)
recevingOb?.sendingVC
recevingOb = nil

//这里是 Bob the Developer的委托保留周期参考的小演示

根据预期的说明,输出类似于:

Receving init
Sender Init
delegate init
Dealocate Receiving
Dealocate SenderVC

但收到输出

Receving init
Sender Init
delegate init

如果我尝试使用下面的代码,我将获得完美的响应。

var recevingOb: RecevingVC? = RecevingVC()
print(recevingOb!.sendingVC)
//recevingOb?.sendingVC
recevingOb = nil

我的问题是,为什么会这样?有人请解释我错了。当我在Xcode中尝试“ didFinishLaunchingWithOptions”方法时,它的工作正常。但是在Playground中,它的行为却很奇怪。我检查了This question,但它并不总是正确的。

0 个答案:

没有答案