我不明白为什么我的对象没有收到通知

I don't understand why my object doesn't receive notifications

我创建了一个自定义 class,看起来像:

class FooDevice: Device {

  private var controller:FooController?
  private var device:Foo?


  override init() {
    super.init()
    if super.authGranted {
      NotificationCenter.default.addObserver(self, selector: #selector(self.discovered(_:)), name: NSNotification.Name(rawValue: FooDiscover), object: nil)
      NotificationCenter.default.addObserver(self, selector: #selector(self.connected(_:)), name: NSNotification.Name(rawValue: FooConnected), object: nil)
    }
  }

  @objc private func discovered(_ notification:Notification) {
    DDLogVerbose("FOO - discovered - \(notification)")
    super.scanner?.stopScanFor(._FOO)
    // TODO: Call super.connector and connect
  }

  @objc private func connected(_ notification:Notification) {
    DDLogVerbose("FOO - connected - \(notification)")
    // Do more stuff after connect
  }


  func start() {
    DDLogVerbose("FOO - startMeasurement()")
    super.scanner?.scanFor(._FOO)
  }  
}

超级class看起来像:

class Device: NSObject {

  private let LICENSE = "my_license"

  private var authenticator:SDKAuthenticator?
  internal var scanner:SDKScanner?
  internal var connector:SDKConnector?
  internal var authGranted = false


  override init() {
    super.init()
    authGranted = self.authRequest(LICENSE)
    if authGranted {
      scanner = SDKScanner.getInstance()
      connector = SDKConnector.getInstance()
    } else {
      // TODO: Show error to user
    }
  }

  private func authRequest(_ data:String) -> Bool {
    // Do stuff using authenticator and authenticated, we can assume we return a true
    return status // true
  }
}

在我的 ViewController 中,我创建了一个 FooDevice 的实例并启动了该过程。我正在做以下事情:

class MyViewController:UIViewController {

 // A lot of properties
 override viewDidLoad() {
   // ViewDidLoad stuff
 }

 @IBAction func connectToDevice(_ sender: Any) {
  // Here I instantiate the object and start the scanning
  let myFooDevice = FooDevice()
  myFooDevice.start()
 }
}

在控制台中,我可以看到扫描仪如何启动并找到蓝牙设备,但未捕获通知且未打印日志。通知名称也是正确的,我敢肯定,因为 SDK return 字符串。

我不知道我错过了什么。希望你能给它一些启发。

您的问题是 ARC 会在任何通知到达之前清理您的 myFooDevice 变量。

您最好将其存储在 属性:

class MyViewController:UIViewController {

    var myFooDevice:FooDevice?

    override viewDidLoad() {
       // ViewDidLoad stuff
    }

    @IBAction func connectToDevice(_ sender: Any) {
        // Here I instantiate the object and start the scanning
        myFooDevice = FooDevice()
        myFooDevice!.start()
    }
}