2012-12-29 24 views
-2

空,我有以下代碼以註冊的觀察者:返回NSUserDefaults的在NSNotificationCenter選擇

// This logs some value 
NSLog(@"%@", [[NSUserDefaults standardUserDefaults] objectForKey:@"myKey"]); 
[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(handleNotifications:) 
              name:SomeNotification 
              object:nil]; 

- (void) handleNotifications: (NSNotification *)notification 
{ 
    // This logs null 
    NSLog(@"%@", [[NSUserDefaults standardUserDefaults] objectForKey:@"myKey"]); 
} 

爲什麼myKey通知選擇返回null?

編輯

我想,當值不存在,在選擇保存新的價值,但它總是出現在應用程序重新啓動後,在選擇器返回null。

- (void) handleNotifications: (NSNotification *)notification 
{ 

    if (![[NSUserDefaults standardUserDefaults] objectForKey:@"myKey"])) { 
    NSLog(@"Saving"); 
    [[NSUserDefaults standardUserDefaults] setObject: @"ABC", forKey:@"myKey"] 
    [[NSUserDefaults standardUserDefaults] synchronize]; 
    } 
} 
+0

要解決您的問題,我們需要更多信息 –

+0

我認爲您需要對「返回」實際執行的操作進行一點閱讀。 –

+4

我很震驚,甚至編譯了這段代碼。這種回報不是很接近正確。 –

回答

0

簡短的回答是,顯然你沒有存入standardUserDefaults爲重點@"myKey"任何物體在那個-handleNotifications:被稱爲和[[NSUserDefaults standardUserDefaults] objectForKey:@"myKey"]回報nil的時間。

您是否正在處理除SomeNotification之外的其他通知?-handleNotifications:?如果是的話,你可以將線

// This logs some value 
NSLog(@"%@", [[NSUserDefaults standardUserDefaults] objectForKey:@"myKey"]); 
[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(handleNotifications:) 
              name:SomeNotification 
              object:nil]; 

執行之前進入-handleNotifications:

+0

這是唯一正在發生的通知。 該代碼塊是AppDelegate'didFinishLaunchingWithOptions'的一部分,它爲'@「myKey」'輸出了一些值,但是當通知稍後觸發時,它將返回'nil'。 Hoever,一個簡單的'NSUserDefaults'保存在通知選擇器或完成塊外。 –

+0

我通過'postNotification'手動測試過,它確實有效。 所以它看起來像Facebook通知:當會話被打開時,'FBSessionDidBecomeOpenActiveSessionNotification'導致問題。 '@「myKey」'在選擇器中返回'nil'來處理'FBSessionDidBecomeOpenActiveSessionNotification' –

+0

看起來我在代碼中犯了一個愚蠢的錯誤。我正在刪除選擇器中某處的值。 感謝您的幫助。 –