【问题标题】:call the function with NSNotificationCenter使用 NSNotificationCenter 调用函数
【发布时间】:2017-06-15 17:19:19
【问题描述】:

我在A班:

-(void)threewaysbuttonshow:(NSNotification *)notification {
    NSLog(@" Do something ");
}

在我的 B 类中,我想调用我的函数,它是 A 类中的threewaysbuttonsho。

我正在考虑使用 NSNotificationCenter。这是我在 B 类中的代码,但在代码运行时它不会调用我的函数,任何帮助表示感谢。

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(threewaysbuttonshow:) name:@"something" object:nil];

【问题讨论】:

    标签: objective-c notifications nsnotificationcenter


    【解决方案1】:

    addObserver:selector:name:object: 呼叫需要在 A 类中,然后在 B 类中,您需要发布通知。像这样:

    @implementation ClassA
    
    - (instancetype)init {
        self = [super init] 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(threewaysbuttonshow:) name:@"something" object:nil];
        return self.
    }
    
    // Remove the observer once the instance is deallocated.
    - (void)dealloc {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
    
    -(void)threewaysbuttonshow:(NSNotification *)notification {
        NSLog(@" Do something ");
    }
    
    @end
    

    不要忘记删除dealloc中的观察者,否则NSNotificationCenter会在实例被释放后调用实例并让你的应用崩溃。

    您发布了来自 B 类的通知:

    [[NSNotificationCenter defaultCenter]postNotificationName:@"something" object:self userInfo:nil];
    

    这将使NSNotificationCenter 调用名称为something 的通知注册的所有方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-05
      相关资源
      最近更新 更多