为什么没有调用协议功能

时间:2014-07-14 22:42:34

标签: swift

我有一个实现协议的文件和另一个调用

的文件
 //
//  DeviceBLE.swift
//

import Foundation
import CoreBlueTooth
import QuartzCore
import UIKit

class DeviceBLE: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate {

    var centralManager : CBCentralManager!

    init() {
        super.init()
        centralManager = CBCentralManager(delegate: self, queue: nil)
    }

    func centralManagerDidUpdateState(central: CBCentralManager!){
        // Determine the state of the peripheral
        if (central.state == .PoweredOff) {
            println("CoreBluetooth BLE hardware is powered off")
        }
        else if (central.state == .PoweredOn) {
            println("CoreBluetooth BLE hardware is powered on and ready")
            //            connectPeripheral(_ peripheral: CBPeripheral!,
            //                options options: [NSObject : AnyObject]!)
        }
        else if (central.state == .Unauthorized) {
            println("CoreBluetooth BLE state is unauthorized")
        }
        else if (central.state == .Unknown) {
            println("CoreBluetooth BLE state is unknown")
        }
        else if (central.state == .Unsupported) {
            println("CoreBluetooth BLE hardware is unsupported on this platform")
        }
    }
}

这是调用文件

//  ViewController.swift
//  BleTest
import Foundation
import CoreBlueTooth
import QuartzCore
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        var myBle = DeviceBLE()
     }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

问题是当实例化DeviceBle时,中心管理器DidUpdateState永远不会被调用。我不明白我做错了什么。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:12)

可能是您将myBle设置为局部变量,因此在viewDidLoad方法执行结束时,将取消分配DeviceBLE。尝试使myBle成为ViewController类的实例变量。

class ViewController: UIViewController {
    var myBle: CBCentralManager?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.myBle = DeviceBLE()
      }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

另外,在你的委托方法中。最好使用switch语句而不是几个if语句。