-(void)viewDidAppear:(BOOL)animated {
NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
[[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationUserDidTakeScreenshotNotification object:nil queue:mainQueue usingBlock:^(NSNotification *note) {
NSLog(@"SShot");
}];
}
- (void)viewWillDisappear:(BOOL)animated{
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationUserDidTakeScreenshotNotification object:nil];
NSLog(@"VWD");
}
-(void)viewDidDisappear:(BOOL)animated {
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationUserDidTakeScreenshotNotification object:nil];
NSLog(@"VDD");
}
即使删除观察者后,我仍在登录SShot
。
还有其他方法可以删除UIApplicationUserDidTakeScreenshotNotification
观察者。
来自Apple Doc:
要注销观察结果,您传递返回的对象以此removeObserver的方法:您必须调用removeObserver:或removeObserver:name:object:由任何指定的对象之前addObserverForName:object:queue:usingBlock:被释放。
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center removeObserver:self.localeChangeObserver];
您正在尝试删除磨损的观察者,self
在这里不是观察者,该观察者是add方法返回的对象
这是在Swift 4中的操作方法...
private var observer: Any!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
observer = NotificationCenter.default.addObserver(forName: NSNotification.Name("SomeNotification"), object: nil, queue: nil) { notification in
//do something
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(observer)
}
哈里斯代码是正确的,除了一个小细节,现在对于Swift 4来说是这样
私人var观察者:任意!而不是私有var观察者:NSObjectProtocol!因此代码应为:
private var observer: Any!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
observer = NotificationCenter.default.addObserver(forName: NSNotification.Name("SomeNotification"), object: nil, queue: nil) { notification in
//do something
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(observer)
}
尝试使用此代码
至添加观察者
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDidTakeScreenshot) name:UIApplicationUserDidTakeScreenshotNotification object:nil];
}
- (void)userDidTakeScreenshot {
// Screenshot taken, act accordingly.
}
和删除特定的观察者
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationUserDidTakeScreenshotNotification object:nil];
}
至删除所有观察者
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
让我知道它是否对您有用!!!!