因此,viewDidUnload
从iOS 6开始不推荐使用,我现在需要做什么?
删除它,并将其中的所有内容迁移didReceiveMemoryWarning
或保留,并且不执行任何操作didReceiveMemoryWarning
?
我在大多数视图控制器中注册了三个观察者.有些人有更多,有些人更少,但我想在父类中包含部分注册和注销过程.即使没有观察者,调用取消注册有什么问题吗?是否要求所有三位观察员取消注册?
- (void)registerForKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationWillEnterBackground:)
name:UIApplicationWillResignActiveNotification
object:nil];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
//Has to be unregistered always, otherwise nav controllers down the line will call this method
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
Run Code Online (Sandbox Code Playgroud) 基本上,我有一个view1,在某些时候,调用view2(via presentModalViewController:animated:
).当UIButton
按下某个视图2时,view2在view1中调用一个通知方法,然后立即关闭.通知方法会弹出警报.
通知方法工作正常,并被适当调用.问题是,每次创建view1时(一次只能存在一个view1),我可能会NSNotification
创建另一个view1因为如果我从view0(菜单)转到view1,然后来回几次,我得到一个一系列相同的警报消息,一个接一个地从通知方法中多次打开一个view1.
这是我的代码,请告诉我我做错了什么:
View1.m
-(void) viewDidLoad {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(showAlert:)
name:@"alert"
object:nil];
}
-(void) showAlert:(NSNotification*)notification {
// (I've also tried to swap the removeObserver method from dealloc
// to here, but it still fails to remove the observer.)
// < UIAlertView code to pop up a message here. >
}
-(void) dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
Run Code Online (Sandbox Code Playgroud)
View2.m
-(IBAction) buttonWasTapped {
[[NSNotificationCenter defaultCenter] postNotificationName:@"alert"
object:nil];
[self dismissModalViewControllerAnimated:YES];
}
-(void) dealloc { …
Run Code Online (Sandbox Code Playgroud) 我有一个基于iOS 5 ARC的项目,并且在我应该删除观察者的位置时遇到困难,NSNotificationCenter
因为我已经注册了UIViewController
.关于SO的类似帖子已经说过这应该在-dealloc
方法中完成.尽管ARC项目中不需要此方法,但我已使用以下代码添加它:
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
Run Code Online (Sandbox Code Playgroud)
作为测试,我打开UIViewController
(在a内UINavigationController
),做一些触发通知的事情,然后通过点击Back按钮将其弹出堆栈.然后UIViewController
,我重新打开,并做更多事情来触发通知,但请注意每个回调被调用两次 - 表明以前的通知尚未注销.重复此过程只会导致每次回调被调用多次,因此它们似乎永远不会取消注册.
任何帮助,将不胜感激!
cocoa-touch objective-c nsnotifications nsnotificationcenter ios