【发布时间】:2016-06-12 16:26:16
【问题描述】:
我正在玩弄一个小型 Swift 应用程序。在其中,用户可以通过单击应用程序菜单中的“新建”来创建任意数量的 MainWindow 实例。
应用程序委托持有一个类型为 MainWindowController 的数组。监视窗口以查找 NSWindowWillCloseNotification 以便从 MainWindowController 数组中删除控制器。
现在的问题是,如果观察者的移除操作正确——我担心可能会有对 observer 的循环引用,但我不知道如何测试:
class ApplicationDelegate: NSObject, NSApplicationDelegate {
private let notificationCenter = NSNotificationCenter.defaultCenter()
private var mainWindowControllers = [MainWindowController]()
func newWindow() {
let mainWindowController = MainWindowController()
let window = mainWindowController.window
var observer: AnyObject?
observer = notificationCenter.addObserverForName(NSWindowWillCloseNotification,
object: window,
queue: nil) { (_) in
// remove the controller from self.mainWindowControllers
self.mainWindowControllers = self.mainWindowControllers.filter() {
$0 !== mainWindowController
}
// remove the observer for this mainWindowController.window
self.notificationCenter.removeObserver(observer!)
}
mainWindowControllers.append(mainWindowController)
}
}
【问题讨论】:
标签: swift nsnotification