2012-10-01 31 views
0

我想在應用程序中保存一些數據在NSUserDefaults中:openURL:sourceApplication:annotation:UIApplicationDelegate中的方法,然後在viewDidLoad中讀取這些數據:在我的主視圖控制器中。但是,數據總是空的!NSUserDefaults爲空

如果我將相同的數據保存在viewDidLoad中:在主視圖控制器中,它立即可見且可恢復,但不是在將它保存在UIApplicationDelegate中時。

這種行爲的任何想法?謝謝。

下面是代碼:

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation 
    { 
     // Save my data 
     [[NSUserDefaults standardUserDefaults] setURL:url forKey:@"url"]; 
     [[NSUserDefaults standardUserDefaults] synchronize]; 
     return YES; 
    } 

- (void)viewDidLoad 
    { 
     [super viewDidLoad]; 

    // It's always false !! 
     if ([[NSUserDefaults standardUserDefaults] URLforKey:@"url"] != nil){ 
     // Do something with url 
     } 
} 
+0

檢查' - (BOOL)申請:(UIApplication的*)應用程序的OpenURL:(NSURL *)網址sourceApplication:(的NSString *)sourceApplication註釋:(ID)註釋 '委託調用或沒有。只有在使用URL架構啓動時,該委託纔會被調用。 – Bharath

+0

@Till。不,我已經評論過這個問題。我在問他實施的代表是否正在調用。 – Bharath

+1

是否曾經援引過這種儲蓄?添加一個NSLog。 – Till

回答

-3

在你的代碼已經在NSUserDefault編程NSURL。嘗試使用NSString。 (即[NSString stringWithFormat:@「%@」,url])。

因此,這將是[[NSUserDefaults standardUserDefaults] setValue:[NSString stringWithFormat:@"%@",url] forKey:@"url"];

+0

該方法被稱爲['setURL:forKey:'](https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/Reference/Reference.html# // apple_ref/doc/uid/20000318-SW36)。如果是'NSStrings',它將被稱爲'setString:forKey:' –

+0

ohh!1對不起。我想寫setvalue。現在我編輯了我的答案。 –

+0

@Foram ..'setURL:'不是'NSString',它是'NSURL'。請在回答問題之前進行驗證 – Bharath

1

最後,problema是viewDidLoad中:的OpenURL::sourceApplication:註釋所以尚未存儲任何值:,在我主視圖控制器比之前應用程序調用。

我必須檢查其他地方的NSUserDefaults。

謝謝你們的幫助!

+0

這種奇怪的行爲是因爲我沒有使用storyboard,而是創建了自己的nib文件,從我的UIApplication委託中以錯誤的方式加載它們。 – jaimeat1