2017-06-15 7 views
0

と機能:コール私はクラスAに持ってNSNotificationCenter

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

と私のクラスBに私はNSNotificationCenterを使用することを考えていたクラスA.

でthreewaysbuttonshoである私の関数を呼び出すしたいと思います。ここで私のコードはBクラスで鳴いていますが、コードが実行されるときに私の関数を呼び出さず、助けに感謝します。

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

答えて

0

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]; 

これは、すべてのメソッドが名前somethingとの通知を登録するNSNotificationCenter呼び出しを行います。

関連する問題