gpt4 book ai didi

ios - 如何在 swift4 中修复 NotificationCenter

转载 作者:行者123 更新时间:2023-11-29 00:18:50 30 4
gpt4 key购买 nike

在从 swift3 到 swift4 的转换过程中,转换器已将 NotificationCenter 更改为以下 View :

 NotificationCenter.default.addObserver(self, selector: #selector(myController.myFunction(_:)), name: NSNotification.Name.NSTextView.didChangeSelectionNotification, object: myNSTextView)

因此,由于 .addObserver() 中的 selector,myFunction 现在前面有 @objc。现在编译器报错,NSNotification.Name 类型没有成员 NSTextView。这是转换器做的,不是我做的。我很困惑。

如何解决这个问题?

更新。我在这里找到了信息How to migrate NSWorkspace notifications to Swift 4?

所以我必须使用

NotificationCenter.default.addObserver(self, selector: #selector(myController.myFunction(_:)), name: NSTextView.didChangeSelectionNotification, object: myNSTextView)  

最佳答案

正如 Gary 的评论中提到的,您需要从调用 Selector 切换过来,而是使用回调。以下示例显示了您需要进行哪些设置才能使其正常工作。

var didBecomeActive: (Notification) -> Void = { notification in
print("app became active")
}

private func setupNotification() {
NotificationCenter.default.addObserver(forName: .UIApplicationDidBecomeActive,
object: nil,
queue: OperationQueue.main,
using: didBecomeActive)
}

首先,我创建了 var didBecomeActive,并将其设为 (Notification) -> Void 类型,以符合函数的预期。在我的示例中,我在回调中保留了 notification 值,但如果您不使用它,则可以将其替换为 _ 并且它会正常工作。

接下来,不调用您使用的函数:

NotificationCenter.default.addObserver(self, selector: #selector(myController.myFunction(_:)), name: NSTextView.didChangeSelectionNotification, object: myNSTextView)  

我调用以下内容:

NotificationCenter.default.addObserver(forName: <#T##NSNotification.Name?#>, 
object: <#T##Any?#>,
queue: <#T##OperationQueue?#>,
using: <#T##(Notification) -> Void#>)

对于 using 参数,只需提供您设置用于接收回调的变量,在本例中为 didBecomeActive

关于ios - 如何在 swift4 中修复 NotificationCenter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44555323/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com