2011-03-30 77 views
8

我創建了一個隨Root.plist文件和本地化目錄en.lproj一起提供的Settings.bundle。iPhone - 讀取Setting.bundle返回錯誤的值

我編輯了Root.plist並添加了幾個我想要用於我的應用程序的設置。

當我從iPhone上刪除應用程序並安裝並第一次運行時,我讀取的所有設置都會返回錯誤的值。例如:

highQualityFlag = [[[NSUserDefaults standardUserDefaults] stringForKey:@"qualityFlag"] boolValue]; 

該標誌爲NO,即使設置默認爲YES。

如果我改變了設置的東西,然後再次運行,後來的運行給我正確的值(ω)

我該怎麼解決呢?

感謝

+0

不同,它[[NSUserDefaults的standardUserDefaults] boolForKey:@ 「qualityFlag」]; ?? – 0x8badf00d 2011-03-30 19:43:43

+0

我用您的建議取代了......完全沒有改變。值繼續相同的錯誤值。 – SpaceDog 2011-03-30 20:10:16

回答

24

試試這個:

- (void)registerDefaultsFromSettingsBundle 
{ 
    NSString *settingsBundle = [[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"bundle"]; 
    if(!settingsBundle) 
    { 
     //NSLog(@"Could not find Settings.bundle"); 
     return; 
    } 

    NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[settingsBundle stringByAppendingPathComponent:@"Root.plist"]]; 
    NSArray *preferences = [settings objectForKey:@"PreferenceSpecifiers"]; 

    NSMutableDictionary *defaultsToRegister = [[NSMutableDictionary alloc] initWithCapacity:[preferences count]]; 
    for(NSDictionary *prefSpecification in preferences) 
    { 
     NSString *key = [prefSpecification objectForKey:@"Key"]; 
     if(key) 
     { 
      [defaultsToRegister setObject:[prefSpecification objectForKey:@"DefaultValue"] forKey:key]; 
     } 
    } 

    [[NSUserDefaults standardUserDefaults] registerDefaults:defaultsToRegister]; 
    [defaultsToRegister release]; 
} 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{  
    [self registerDefaultsFromSettingsBundle]; 

    window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 
     [window makeKeyAndVisible]; 
    return YES; 
} 
+0

YESSSSSSSSSSSSSSSSSSSS !!!!!!!!!!!!!!!!!!!!!!!!!!只是一個小問題:我需要添加[self registerDefaultsFromSettingsBundle];到applicationDidBecomeActive或applicationWillEnterForeground? – SpaceDog 2011-03-30 20:26:21

+0

跟進問題:我發佈了這個問題:http://stackoverflow.com/questions/8766979/nsuserdefaults-settings-bundle-plist我基本上想要用戶輸入一個url值來在應用程序中使用。截至目前,用戶可以輸入並保存它,但在應用程序啓動時不會回讀。硬編碼到plist的默認值就是讀取的內容。請有人指出我的錯在哪裏嗎?爲什麼該應用仍在讀取默認的佔位符值? – marciokoko 2012-01-09 23:09:06

+0

@marciokoko你最終得到了一個解決你的問題。我面對相同! – pnizzle 2013-01-14 01:06:22