Swift 5.5:当通知对象必须在主队列上处理时,如何正确访问通知处理程序内的通知对象?

问题描述 投票:0回答:1

这个最小的例子

class ViewController : NSViewController {
    override func loadView() {
        NotificationCenter.default.addObserver(forName: NSView.frameDidChangeNotification, object: view, queue: .main) { [self] n in
            DispatchQueue.main.async {
                self.resizeSubviews(animate: false, sender: n.object) // <- warning here
            }
        }
    }

    func resizeSubviews(animate: Bool, sender: Any?) {
    }
}

导致警告:

Capture of 'n' with non-sendable type 'Notification' in a `@Sendable` closure

虽然在添加观察者时已经要求主调度队列,但我必须将

resizeSubviews
调用包装在
DispatchQueue.main.async
块中。

如何正确访问通知处理程序中的 n ?

swift cocoa
1个回答
0
投票

通知是不可发送的类型,不要在闭包内使用它。

n.object
的类型为
Any?
,将其转换为
NSView

NotificationCenter.default.addObserver(forName: NSView.frameDidChangeNotification, object: view, queue: .main) { [self] n in
    guard let sender = n.object as? NSView else { return }
    DispatchQueue.main.async {
        self.resizeSubviews(animate: false, sender: sender)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.