【发布时间】:2018-03-10 07:45:37
【问题描述】:
我正在使用 NSNotificationCenter 在我的代码中发送本地通知,并在 Objective-C 和 Swift 中工作。我正在从 Objective-C 发布通知并在 Swift 中接收。但是我在通知中添加的方法被多次调用并仅在viewDidLoad 方法中添加了观察者。
斯威夫特:
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector:#selector(MainScreen.serverCardSynced), name: NSNotification.Name(rawValue: NOTIF_SERVER_CARD_SYNCED), object: nil);
NotificationCenter.default.addObserver(self, selector:#selector(MainScreen.checkForAutoSync), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil);
NotificationCenter.default.addObserver(self, selector:#selector(MainScreen.initateSync), name: NSNotification.Name(rawValue: NOTIF_CONTACT_ENTITY_CHANGE), object:nil);
NotificationCenter.default.addObserver(self, selector:#selector(MainScreen.menuRemoved), name: NSNotification.Name(rawValue: NOTIF_MENU_REMOVED), object:nil);
NotificationCenter.default.addObserver(self, selector:#selector(MainScreen.reloadAllCards(_:)), name: NSNotification.Name(rawValue: NOTIF_RELOAD_ALL_CARDS), object:nil);
NotificationCenter.default.addObserver(self, selector:#selector(MainScreen.initateDownloadMyCards), name: NSNotification.Name(rawValue: NOTIF_DOWNLOAD_CARD), object:nil);
}
目标-C:
- (void)applicationDidBecomeActive:(UIApplication *)application {
self.isSyncPending = true;
[[NSNotificationCenter defaultCenter]
postNotificationName:NOTIF_CONTACT_ENTITY_CHANGE object:nil];
}
-(void)insertData(){
[[NSNotificationCenter defaultCenter]
postNotificationName:NOTIF_SERVER_CARD_SYNCED object:nil];
}
我在deinit 中添加了删除观察者,但它甚至没有调用。如何停止多次调用。
【问题讨论】:
-
移除视图中的观察者将消失
-
我试过了,但它甚至没有调用那个特定的方法
-
我也在应用程序中发布通知确实变得活跃,所以如何删除观察者,否则每次我来自后台时它都会调用多次
标签: ios objective-c swift nsnotificationcenter addobserver