2013-02-20 88 views
-1

我打電話通知另一類如何從另一個類

//這是ClassA的

- (void)onDidFinishLaunchingNotification:(NSNotification*)notification 
{ 
    NSLOG(@"onDidFinishLaunchingNotification"); 
} 

從另一個類 //這是B級呼叫通知呼叫通知

[[NSNotificationCenter defaultCenter]addObserver:nil selector:@selector(onDidFinishLaunchingNotification:) name:nil object:nil]; 

回答

1

在A類中,添加自我作爲通知的觀察者名稱

[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(onDidFinishLaunchingNotification:) 
              name:YourOnDidFinishLaunchingNotificationName 
              object:nil]; 

和B類,使用-postNotificationName:object:張貼通知:

[[NSNotificationCenter defaultCenter] postNotificationName:YourOnDidFinishLaunchingNotificationName 
                object:nil]; 
+0

當我打電話時[[NSNotificationCenter defaultCenter] postNotificationName:YourOnDidFinishLaunchingNotificationName object:nil];我的應用程序崩潰了! – kiran 2013-02-24 00:47:18

+0

@kiran確保'selector'與消息名稱相同:'onDidFinishLaunchingNotification:',不要忘記COLON。 – Kjuly 2013-02-24 02:39:11

1

B類你shuold的addObserver到B是這樣的:

[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(onDidFinishLaunchingNotification:) 
              name:YourOnDidFinishLaunchingNotificationName 
              object:nil]; 

我想你應該看看addObserver:selector:name:object:

這裏是一個非常useful example使用NSNotification