我有一个客观的C类.在其中,我创建了一个init方法并在其中设置了NSNotification
//Set up NSNotification
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(getData)
name:@"Answer Submitted"
object:nil];
Run Code Online (Sandbox Code Playgroud)
我在哪里设置[[NSNotificationCenter defaultCenter] removeObserver:self]这门课程?我知道,对于a UIViewController,我可以将它添加到viewDidUnload方法中如果我刚刚创建了一个目标c类,需要做什么?
在App中,我使用了几个viewcontrollers.在一个viewcontroller上,一个观察者初始化如下:
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"MyNotification" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myMethod:) name:@"MyNotification" object:nil];
Run Code Online (Sandbox Code Playgroud)
即使NSNotification在初始化之前移除了执行次数,myMethod:也可以通过相应视图控制器上的重复视图量来总结.
为什么会发生这种情况?如何避免myMethod:被调用一次以上.
注意:我通过使用断点确保多次调用postNotification时没有犯错.
编辑:这就是我的postNotification的样子
NSArray * objects = [NSArray arrayWithObjects:[NSNumber numberWithInt:number],someText, nil];
NSArray * keys = [NSArray arrayWithObjects:@"Number",@"Text", nil];
NSDictionary * userInfo = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
[[NSNotificationCenter defaultCenter] postNotificationName:@"myNotification" object:self userInfo:userInfo];
Run Code Online (Sandbox Code Playgroud)
编辑:甚至在我订阅了viewwillappear之后:我得到了相同的结果.myMethod:被多次调用.(我重新加载viewcontroller的次数).
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"MyNotification" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myMethod:) name:@"MyNotification" object:nil];
}
Run Code Online (Sandbox Code Playgroud)
编辑:我的生命周期似乎有些问题.ViewDidUnload和dealloc没有被调用,但是viewdiddisappear被调用.
我将Viewcontroller推送到堆栈的方式如下,其中parent是tableview子类(单击此viewcontroller启动的行:
detailScreen * screen = [[detailScreen alloc] initWithContentID:ID andFullContentArray:fullContentIndex andParent:parent];
[self.navigationController pushViewController:screen animated:YES];
Run Code Online (Sandbox Code Playgroud)
解:
将nsnotification移除到viewdiddisappear就可以了.感谢您的指导!
iphone nsnotifications uiviewcontroller nsnotificationcenter ios
我有UIViewController这个方法:
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
NSLog(@"DISAPPEAR");
lastKnownOrientation = [self interfaceOrientation];
}
-(void)openSendVC{
SendMsgViewController *vc = [[SendMsgViewController alloc]initWithNibName:@"SendMsgViewController" bundle:nil];
[self.navigationController pushViewController:vc animated:NO];
}
Run Code Online (Sandbox Code Playgroud)
在第二个视图controller(SendMsgViewController)中,viewDidLoad我有以下内容:
[self presentViewController:picker animated:YES completion:NULL];
Run Code Online (Sandbox Code Playgroud)
挑选者是一个UIImageViewPicker.
问题是,当我调用该方法时,openSendVC会打开一个新的控制器,但是viewWillDisappear(第一个viewController)没有被调用.