我遵循dreammlax示例,但我似乎无法让我的NSNotification工作。是否需要添加框架或其他内容?我如何调试代码。
#import "FirstViewController.h"
@interface FirstViewController ()
@end
@implementation FirstViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)btnSend:(id)sender {
[[NSNotificationCenter defaultCenter] postNotificationName:@"TestNotification"
object:self];
self.tabBarController.selectedIndex = 1;
}
@end
#import "SecondViewController.h"
@interface SecondViewController ()
@end
@implementation SecondViewController
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(receiveTestNotification:)
name:@"TestNotification"
object:nil];
//===Removed ===[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void) receiveTestNotification:(NSNotification *) notification
{
if ([[notification name] isEqualToString:@"TestNotification"])
NSLog (@"Successfully received the test notification!");
}
@end
答案 0 :(得分:2)
添加观察者后删除[[NSNotificationCenter defaultCenter] removeObserver:self];
,它将起作用
或者您可以将[[NSNotificationCenter defaultCenter] removeObserver:self];
移至dealloc
方法
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
关于第一次运行时无效的问题。
这是因为在初始化postNotificationName
之前调用了SecondViewController
。要解决此问题,请尝试以下代码。
- (IBAction)btnSend:(id)sender {
self.tabBarController.selectedIndex = 1;
[[NSNotificationCenter defaultCenter] postNotificationName:@"TestNotification"
object:self];
}
答案 1 :(得分:0)
// from where u want to post notification
- (IBAction)PressedMeBtn:(id)sender {
KNcreateOfferBack is define string!!!!
[[NSNotificationCenter defaultCenter] postNotificationName:KNcreateOfferBack object:nil];
}
//And where you are sending notification and observer
- (void)BackFromControllers:(NSNotification *)note {
NSLog(@"Received Notification Inside LeftMenu - event");
if([[note name] isEqualToString:KNcreateOfferBack]){
NSLog(@"KNcreateOfferBack NoteName :***: %@ :***:",note.name);
// done your work here and then remove your notification !!!!
[[NSNotificationCenter defaultCenter] removeObserver:self name:KNcreateOfferBack object:nil];
}
// use observer in viewWillAppear where you are using above method
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(BackFromControllers:)
name:KNcreateOfferBack object:nil];
}