我一直在尝试让NSNotification正常工作。作为测试,我想要一个使用storyBoards加载新viewController的按钮。当你点击按钮时,它应该触发一个通知,让appObserver在第二个ViewController (我已经命名为Page2)中拾取。在Page2中,NSNotificationCenter应该启动一个方法(myMethod:)并打印出一个简单的NSLog。不幸的是,它不能工作,因为myMethod没有被调用。我做错了什么?
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (IBAction)goToPage2Button:(id)sender {
[[NSNotificationCenter defaultCenter] postNotificationName:@"test" object:nil];
}
#import "Page2.h"
@interface Page2 ()
@end
@implementation Page2
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(myMethod:) name:@"test" object:nil];
}
return self;
}
-(void)myMethod:(NSNotification *)notification{
if ([[notification name] isEqualToString:@"test"])
NSLog (@"Successfully received the test notification!");
}发布于 2012-11-24 23:19:06
我认为这可能是因为当通知被触发时,您的page2视图控制器不存在。
第二个视图控制器在从nib唤醒时注册观察,但是如果它还没有创建,那么它就没有注册第一个视图控制器正在发送的通知。
您应该做的是使用segues根据操作加载视图控制器。
发布于 2012-11-24 23:29:54
使用情节提要时,通常不会调用initWithNibName。它使用initWithCoder。您确定您正在执行添加您的观察者的代码行吗?
如果您曾经得到看起来某行代码没有被调用的行为,最好在那里放置一个断点或一个NSLog,并确认它确实被调用了。
https://stackoverflow.com/questions/13542492
复制相似问题