简体   繁体   中英

Swift class function not being called

I have the following class written in Swift :

import UIKit
import CoreBluetooth

class vaBean: CBCentralManager, CBCentralManagerDelegate {

func centralManagerDidUpdateState(central: CBCentralManager!) {
    println("didUpdateState")
    switch (central.state) {
    case .PoweredOff:
        println("hardware is powered off")

    case .PoweredOn:
        println("hardware is powered on and ready")

    case .Resetting:
        println("hardware is resetting")

    case .Unauthorized:
        println("state is unauthorized")

    case .Unknown:
        println("state is unknown");

    case .Unsupported:
        println("hardware is unsupported on this platform");

    }
}
}

Which I then create an instance of in my main ViewController using the following code:

import UIKit
import CoreBluetooth

class ViewController: UIViewController {

override func viewDidLoad() {
    println("bluetoothTest v1.00")
    super.viewDidLoad()
    var myBean: vaBean!
    var myBeanMgr = vaBean(delegate: myBean, queue: nil)
}

override func didReceiveMemoryWarning() {super.didReceiveMemoryWarning()}
}

The code compiles OK but the function centralManagerDidUpdateState is never called and I'm not sure why.

Consider these lines:

var myBean: vaBean!
var myBeanMgr = vaBean(delegate: myBean, queue: nil)

After that, what is myBean ? It is nil! You have created a variable and declared its type, but you have never assigned it any object. So you then create myBeanMgr with its delegate being myBean , which is nil. You have an object with a nil delegate. There is no one home to receive the delegate messages.

Moreover, viewDidLoad then ends and all the local variables including myBeanMgr are instantly destroyed. So now you don't even have myBeanMgr any more. You have nothing . No CBCentralManager. No CBCentralManagerDelegate. Nothing.

So, you need to study memory management so that you know why and how things persist, and you need to learn the basics of Swift so that you understand how to instantiate a class. Your code shows clearly that you don't understand either of those things. They are very basic so go no further until you do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM