我关注了 dreammlax例如,但我似乎无法让我的 NSNotification 工作。是否有框架或我需要添加的东西?我如何调试代码。
FirstViewController 发布
#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
SecondViewController 接收
#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
最佳答案
添加观察者后删除[[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];
}
关于ios - NSNotificationCenter 不工作,如何调试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49891619/