我一直在努力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!");
}