ios - Swift 中的通知观察者错误

标签 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 指南,就会发现评论中其他用户也遇到了同样的问题,因此这不仅仅与我的代码有关

有人知道怎么解决吗?

最佳答案

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

我的自定义观察者

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

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

就是这样!它不像观察者那么强大,但在大多数情况下它是完成工作的简单、快速的方法!

关于ios - Swift 中的通知观察者错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41004491/

相关文章:

ios - Backspace (\b) 在swift语言中等价

ios - 快速制作集合类(数组、字典)的浅拷贝,而不是深拷贝。

mvvm - 淘汰赛2 : How to delay observable object.

javascript - 如何使用不可变对象(immutable对象)替代观察者模式

ios - 这张图片使用了什么样的 View

ios - 禁用 UIScrollView 上的点击

objective-c - 如何将选定的 TableView 值发送回不同的 View ?

ios - Swift 显示字典类型的 nil 值

c++ - 访问声明只能应用于基类成员

iphone - 在 Xcode 中将 iPhone 目标应用程序转换为 Universal