2015-09-04 42 views
2

試圖讓一個ViewController通過標準的可可通知與另一個通信。如何訪問iOS通知中傳遞的數據(簡單)?

寫了一個簡單的測試用例。在我最初的VC我添加以下viewDidLoad中:

[[NSNotificationCenter defaultCenter] addObserver:self 
selector: @selector(mesageReceived:) 
name:@"test.channel.pw" object:nil]; 

我添加下面的方法:

- (void)mesageReceived:(NSNotification *)notif 
{ 
    NSString *text = (NSString *)notif;  
} 

我再原因請看它具有以下添加到其viewDidLoad中一個VC:

NSString *test = @"someText"; 
[[NSNotificationCenter defaultCenter] 
    postNotificationName:@"test.channel.pw" object:test]; 

當我運行它時,通知工作 - messageReceived方法被調用 - 但文本的值是「test.channel.pw」,而不是「someText」,如我所料。

這裏發生了什麼,以及使用通知將類引用傳遞給類實例的正確語法是什麼?

+0

可能重複的[如何傳遞對象與NSNotificationCenter](http://stackoverflow.com/questions/7896646/how-to-pass-object-with-nnnnotificationcenter) –

回答

0

您需要使用userInfo字典傳遞您的數據。

更改通知傳遞這樣的代碼:

[[NSNotificationCenter defaultCenter] postNotificationName:@"test.channel.pw" object:nil userInfo:[NSDictionary dictionaryWithObject:@"someText" forKey:@"dataKey"]]; 

和變革,如接收器方法:

- (void)mesageReceived:(NSNotification *)notif 
{ 
    NSString *text = [[notif userInfo] objectForKey:@"dataKey"];  
} 
0

嘗試NSString *text = (NSString *)[notif object];

0

通過這個

-(void)someMethod{ 
    NSDictionary *postDict = @{@"Key":[NSNumber numberWithFloat:17.0]}; 
[[NSNotificationCenter defaultCenter]postNotificationName:@"myNotification" object:postDict]; 
} 

一些其他類

-(void)viewDidLoad{ 
[[NSNotificationCenter defaultCenter]postNotificationName:@"myNotification" object:nil userInfo:postDict]; 
} 
-(void)valueForNotification:(NSNotification *)notification{ 
NSDictionary *dict = [notification userInfo]; 
NSLog(@"%@",[dict objectForKey:@"Key"]); //prints out 17.0 
} 
0

你需要傳遞只的NSDictionary對象NSnotificationCenter。通過NSDictionary你可以傳遞任何數據,然後你需要解析一次收到。

相關問題