在 Swift 中添加 Observer 和 Selector 3

Add Observer and Selector in Swift 3

我真的很难理解观察者的新语法。

你能帮我把这个翻译成Swift 3.

nc.addObserver(self, selector: #selector(MapViewController.locationUpdated(_:)), name: LocationNotification.kLocationUpdated, object: nil)
nc.addObserver(self, selector: #selector(MapViewController.locationAuthorizationStatusChanged(_:)), name: LocationNotification.kAuthorizationStatusChanged, object: nil)
nc.addObserver(self, selector: #selector(MapViewController.locationManagerDidFailWithError(_:)), name: LocationNotification.kLocationManagerDidFailWithError, object: nil)

非常感谢!

您的代码语法适用于 Swift 3。使用此语法,我假设您的 LocationNotification 对象看起来像这样:

struct LocationNotification {
    static let kLocationUpdated = Notification.Name(rawValue: "LocationUpdated")
    static let kAuthorizationStatusChanged = Notification.Name(rawValue: "AuthorizationStatusChanged")
    static let kLocationManagerDidFailWithError = Notification.Name(rawValue: "LocationManagerDidFailWithError")
}

记得让方法接受通知public(如果它在不同的控制器上)。

并且您还应该添加处理器标记 objc,以便 objective-c 方法可以调用它。

指定观察员:

nc.addObserver(
    self,
    selector: #selector(received(notification:)),
    name: LocationNotification.kLocationUpdated, object: nil
)

处理通知:

@objc public func locationUpdated(notification:Notification) {
    //Do something
}

希望对您有所帮助! :-)