ios - NSNotificationCenter 不工作,如何调试

标签 ios objective-c nsnotificationcenter

我关注了 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];
}

关于为什么它在第一次运行时不起作用的问题。

这是因为 postNotificationNameSecondViewController 初始化之前被调用了。要修复它,请尝试以下代码。

- (IBAction)btnSend:(id)sender {
    self.tabBarController.selectedIndex = 1;

    [[NSNotificationCenter defaultCenter] postNotificationName:@"TestNotification" 
      object:self];
}

关于ios - NSNotificationCenter 不工作,如何调试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49891619/

相关文章:

iphone - 为什么我不能使用 NSDateFormatter dateFromString 从 NSString 获取年份?

ios - snapchat 如何调整图像大小?

ios - +load 方法没有在 iOS 中被调用?

ios - 自定义事件指示器不起作用( objective-c )

ios - 从通知中心删除观察者的最佳位置在哪里

ios - 在不打开 ViewController 的情况下订阅 NotificationCenter

javascript - 如何在 Xamarin iOS 项目中评估 JavaScript 并获得结果?

ios - 使用变量更改 UIButton 图像

iphone - 应用程序进入后台时的内存占用

swift - 文本字段帧动画与键盘动画持续时间不同步