【问题标题】:I don't understand why my object doesn't receive notifications我不明白为什么我的对象没有收到通知
【发布时间】:2020-06-02 13:47:12
【问题描述】:

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

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】:

    您的问题是 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()
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多