什麼是初始化CBCentralManager實例的好方法,CBCentralManager需要委託並且通常指向擁有的類?如何在需要自引用時在Swift中初始化CBCentralManager
我可以聲明該屬性是一個隱式解包可選,但這樣做,因爲一般的做法似乎並不像Swift一樣,也不是很安全。
或者,我可以聲明該屬性爲可選項。但是由於CBCentralManager的初始化器沒有聲明爲failable,因此聲明實例似乎沒有意義。
隱無包裝可選:
class MyUnwrappedOptional: NSObject, CBCentralManagerDelegate {
var centralManager: CBCentralManager!
func init() {
super.init()
centralManager = CBCentralManager(delegate: self, queue: nil, options:nil)
// Subsequent usages of centralManager in other methods of this class don't require additional unwrapping.
centralManager.scanForPeripheralsWithServices(services, options: nil)
}
}
使用可選:
class MyOptionalClass: NSObject, CBCentralManagerDelegate {
var centralManager: CBCentralManager?
func init() {
super.init()
centralManager = CBCentralManager(delegate: self, queue: nil, options:nil)
// Subsequent usages of centralManager in other methods of this class require optional checks:
if let central = centralManager {
central.scanForPeripheralsWithServices(services, options: nil)
}
// :: or ::
central!.scanForPeripheralsWithServices(services, options: nil)
}
}
或者是這些更優選或有另一種方式來實現這一目標?