如何正确在 Swift 中使用 NSNotificationCenter (addObserver):解析语法与取消订阅
你好!我刚开始学习 Swift,并尝试通过 NSNotificationCenter 在两个 ViewController 之间实现数据交换。在 Objective-C 中,我见过这样的语法:
```objc
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:@"MyNotification" object:nil];
```
但在 Swift 中我搞混了。我尝试这样写:
```swift
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleNotification:", name: "MyNotification", object: nil)
```
但 Xcode 报错说 selector 需要使用 #selector。我重写了:
```swift
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(handleNotification), name: "MyNotification", object: nil)
```
但现在我不明白如何正确声明 handleNotification 方法。它是否需要接受 Notification 参数?另外,我听说必须取消订阅通知,否则会导致内存泄漏。在 Swift 中如何正确做到这一点?请展示一下。