2017-06-15 62 views
0

我有A類:調用函數與NSNotificationCenter

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

,並在我的B級我想打電話給我的功能是threewaysbuttonsho類A.

我想用NSNotificationCenter。這裏是我在B類中的代碼,但是在代碼運行時它不會調用我的函數,任何幫助都可以欣賞。

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

回答

0

addObserver:selector:name:object:調用需要在一個類,然後在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通知。