Swift 2.1使用NSObject进行委派

时间:2016-02-01 00:56:25

标签: swift2 ios9 delegation

我正在查看下面的示例并收到错误消息:

Cannot convert value of type 'NSObject -> () -> CentralViewController   
to expected argument type 'TransferServiceDelegate?'

我正在尝试完成一个代表团,当我尝试初始化'扫描仪'时,它正在犯错。任何帮助将不胜感激。谢谢!:

import UIKit
import Foundation


protocol TransferServiceScannerDelegate: NSObjectProtocol {
    func didStartScan()
    func didStopScan()
    func didTransferData(data: NSData?)
}

class TransferServiceScanner: NSObject{
    weak var delegate: TransferServiceScannerDelegate?

    init(delegate: TransferServiceScannerDelegate?) {
        self.delegate = delegate
        super.init()
    }

}

class CentralViewController: UIViewController,
TransferServiceScannerDelegate {

   *let scanner: TransferServiceScanner = TransferServiceScanner(self)*

   func didStartScan(){}
   func didStopScan(){}
   func didTransferData(data: NSData?){}

}

1 个答案:

答案 0 :(得分:1)

第一种方式:

lazy var scanner: TransferServiceScanner = {
        let scanner = TransferServiceScanner(delegate: self)
        return scanner
    }()

我不认为在init中使用delegate是一种好方法和必要,你也可以这样做:

class TransferServiceScanner: NSObject{
    weak var delegate: TransferServiceScannerDelegate?

    init(delegate: TransferServiceScannerDelegate?) {
        self.delegate = delegate
        super.init()
    }

    override init() {
        super.init()
    }
}

class CentralViewController: UIViewController,
TransferServiceScannerDelegate {

    var scanner: TransferServiceScanner = TransferServiceScanner()

    func didStartScan(){}
    func didStopScan(){}
    func didTransferData(data: NSData?){}

    override func viewDidLoad() {
        super.viewDidLoad()
        scanner.delegate = self
    }
}