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

问题描述 投票:0回答:1

我创建了一个自定义类,如下所示:

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 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返回了字符串。

我不知道我在想什么。希望您能对此有所了解。

ios swift memory-management nsnotificationcenter
1个回答
1
投票

您的问题是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()
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.