简体   繁体   English

Swift类函数未调用

[英]Swift class function not being called

I have the following class written in Swift : 我有以下用Swift编写的class

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: 然后,我使用以下代码在主ViewController创建的实例:

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. 该代码编译正常,但从未调用函数centralManagerDidUpdateState ,我不确定为什么。

Consider these lines: 考虑以下几行:

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

After that, what is myBean ? 之后,什么是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. 因此,然后创建myBeanMgr ,其委托为myBean ,为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. 此外, viewDidLoad随后结束,包括myBeanMgr在内的所有局部变量均被立即销毁。 So now you don't even have myBeanMgr any more. 因此,现在您甚至都没有myBeanMgr You have nothing . 什么没有 No CBCentralManager. 没有CBCentralManager。 No CBCentralManagerDelegate. 没有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. 因此,您需要学习内存管理,以便了解事物为什么以及如何持续存在,还需要学习Swift的基础知识,从而了解如何实例化类。 Your code shows clearly that you don't understand either of those things. 您的代码清楚地表明您不了解其中任何一件事。 They are very basic so go no further until you do. 它们非常基础,因此除非您做不到,否则请不要再说了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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