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

时间:2020-02-18 13:58:39

标签: ios swift memory-management nsnotificationcenter

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

Class 1 - call Class 2
Class 2 - call Class 3
Class 3 try/catch an error
log.getLogs returns all logged informations from Class 1..3

超类如下:

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)
  }  
}

在ViewController中,我创建一个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 } } 的实例并开始该过程。我正在做以下事情:

FooDevice

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

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

1 个答案:

答案 0 :(得分:2)

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