我一直试图让NSNotification
工作。对于测试,我想要一个使用storyBoards加载新viewController的按钮。当你点击按钮时,它应该触发appObserver在第二个ViewController(我已经命名为Page2)中的通知。在Page2中,NSNotificationCenter
应该启动一个方法(myMethod :)并打印出一个简单的NSLog
。 不幸的是,它不起作用,因为myMethod没有被调用。我究竟做错了什么 ???NS通知不起作用
#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!");
}
@Abizem - 感谢您让我走向正确的方向。我刚刚学会了如何使用segues传递数据,并且它工作得非常出色。 – pete