0

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.

Roo
  • 259
  • 1
  • 3
  • 15

1 Answers1

1

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.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • 1
    Also, stop using small letters to start the names of classes. Stop it _now_. You are just confusing yourself. – matt Oct 31 '14 at 15:41
  • Also, you really want to subclass CBCentralManager? And you really want the same object to be both a CBCentralManager and a CBCentralManagerDelegate? Really? _Really?_ – matt Oct 31 '14 at 15:42