【问题标题】:Why is the protocol function not being called为什么没有调用协议函数
【发布时间】:2014-07-14 22:42:34
【问题描述】:

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

 //
//  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 被实例化时,centralManagerDidUpdateState 永远不会被调用。我不明白我做错了什么。有人可以帮忙吗?

【问题讨论】:

    标签: swift


    【解决方案1】:

    可能是您将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 语句。

    【讨论】:

    • 谢谢。这解决了这个问题。它不会让我投票给你。不过还是谢谢。
    • 您能否通过单击我帖子左上角的对勾将答案标记为正确?
    猜你喜欢
    • 2016-09-29
    • 1970-01-01
    • 1970-01-01
    • 2015-08-05
    • 2012-05-06
    • 2013-02-16
    • 1970-01-01
    • 2017-08-15
    • 2023-04-10
    相关资源
    最近更新 更多