Swift中的通知观察者错误

时间:2016-12-06 20:42:31

标签: ios swift observer-pattern

我正在使用this IAP implementation guide,当购买最终时,它会使用以下代码发布通知:

NotificationCenter.default.post(name: NSNotification.Name(rawValue: IAPHelper.IAPHelperPurchaseNotification), object: identifier)

该实现不包含观察者代码,因此我将以下内容添加到按下“购买”按钮时运行的函数中:

var functionToRun = #selector(MyViewController.runAfterBoughtFunc)
NotificationCenter.default.addObserver(self, selector: functionToRun, name: NSNotification.Name(rawValue: IAPHelper.IAPHelperPurchaseNotification), object:nil)

我的问题是,当调用NotificationCenter.default.post(...)代码时,我收到此错误:

...runAfterBoughtFuncWithNotif:]: unrecognized selector sent to instance 0x100f12fc0
(lldb) 

备注

  1. 如果我注释掉观察者代码,我就不会再出错了。
  2. 如果您查看我正在使用的IAP指南,在评论中其他用户遇到了同样的问题,因此这不仅仅与我的代码隔离
  3. 任何人都知道如何修复它?

1 个答案:

答案 0 :(得分:0)

由于没有发布答案,我不得不想出一个解决方法。因此,如果您在使用观察者模式时遇到问题,可以尝试这种替代方案。

我的自定义观察器

下面的代码有一个变量来保存被观察事物的状态。然后它使用一个计时器来定期运行一个函数,该函数检查该变量以查看状态是否发生了变化。以下示例是观察购买状态。

  1. 设置一个指向我们自定义观察者的变量,我的是checkPurchase状态。您很可能希望将其添加到按钮推送代码或viewDidLoad,无论如何设置。

    let selector = #selector(myViewController.checkPurchaseStatus)
    
  2. 然后设置一个定时运行的定时器来运行该功能,在我的情况下它会运行" checkPurchaseStatus"每秒一次。在上面的代码下添加它。

    timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: selector, userInfo: nil, repeats: true)
    
  3. 然后设置一个跟踪"状态"的变量。如果状态将由另一个ViewController确定,则可以将其设为全局变量:

    var purchaseState = ""
    
  4. 列出项目

    func checkPurchaseStatus () {
        switch purchaseState {
        case "":
            print("Waiting for purchase...")
        case "failed":
            timer.invalidate() //turns timer off
            purchaseState = "" //resets the variable for future uses
            //Add more code to be run if the purchase failed
            print("Purchased failed. Timer stopped.")
        case "succeeded":
            timer.invalidate() //turns timer off
            purchaseState = "" //resets the variable for future uses
            //Add more code to be run if the purchase succeeded
            print("Purchased succeeded. Timer stopped.")
        default:
            break
        }
    }
    
  5. 那就是它!它不像观察者那样强大,但它是在大多数情况下完成工作的一种简单,快捷的方式!

相关问题