Swift 2.1 使用 NSObject 委托
Swift 2.1 Delegation with NSObject
我正在处理下面的示例并收到一条错误消息:
Cannot convert value of type 'NSObject -> () -> CentralViewController
to expected argument type 'TransferServiceDelegate?'
我正在尝试完成委托,但在我尝试初始化时出现错误 'scanner'。任何帮助将不胜感激..谢谢!:
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?){}
}
第一种方式:
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
}
}
我正在处理下面的示例并收到一条错误消息:
Cannot convert value of type 'NSObject -> () -> CentralViewController
to expected argument type 'TransferServiceDelegate?'
我正在尝试完成委托,但在我尝试初始化时出现错误 'scanner'。任何帮助将不胜感激..谢谢!:
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?){}
}
第一种方式:
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
}
}