使用 NSObject 的 Swift 2.1 委托
Posted
技术标签:
【中文标题】使用 NSObject 的 Swift 2.1 委托【英文标题】:Swift 2.1 Delegation with NSObject 【发布时间】:2016-02-01 00:56:25 【问题描述】:我正在处理下面的示例并收到一条错误消息:
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】:第一种方式:
lazy var scanner: TransferServiceScanner =
let scanner = TransferServiceScanner(delegate: self)
return scanner
()
我不认为在 init 中使用委托是一个好方法和必要的,你也可以这样做:
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
【讨论】:
以上是关于使用 NSObject 的 Swift 2.1 委托的主要内容,如果未能解决你的问题,请参考以下文章
使用 Swift iOS 中的 Javascriptcore 框架将 NSobject 传递给 javascript
子类化 NSObject 和使用泛型时 Swift 编译错误