类不符合Protocol CBPeripheralManager Delegate

时间:2015-03-17 12:08:30

标签: ios xcode swift core-bluetooth

我是IOS swift开发的新手,我正在实现一个PeripheralHandler类,我正在初始化一个CBPeripheralManager实例。我已经实现了所需的委托方法,但仍显示错误'Type PeripheralHandler ->() -> PeripheralHandler!' does not confirm to CBPeripheralManagerDelegate.

import Foundation
import CoreBluetooth

class PeripheralHandler : NSObject, CBPeripheralManagerDelegate{

    var myPeripheralManager = CBPeripheralManager(delegate:self, queue: nil)

    func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager!)
    {
        println("peripheralManagerDidUpdateState called !!!")

        switch peripheral.state
        {
        case CBPeripheralManagerState.PoweredOff:
            println("BLE OFF")
        case CBPeripheralManagerState.PoweredOn:
            println("BLE ON")
        case CBPeripheralManagerState.Unknown:
            println("NOT RECOGNIZED")
        case CBPeripheralManagerState.Unsupported:
            println("BLE NOT SUPPORTED")
        case CBPeripheralManagerState.Resetting:
            println("BLE NOT SUPPORTED")
        default:
            println("Error")
        }
    }
}

1 个答案:

答案 0 :(得分:2)

这是一个误导性的错误消息。您无法在实例变量的初始分配中引用self。当实例变量被实例化时,self并不一定包含任何有意义的东西,因此Swift不允许使用self。

您可以使用惰性变量:

lazy var myPeripheralManager: CBPeripheralManager = {
    return CBPeripheralManager(delegate:self, queue: nil)
}()

首次访问myPeripheralManager时会调用此块,它会为您创建对象。