Saturday, September 22, 2012

How to use NSUserDefaults


AppDelegate.m
//Use NSDate to determine that App first run or not
NSString *dateKey = @"dateKey";
NSDate *lastRead = (NSDate *)[[NSUserDefaults standardUserDefaults] objectForKey:dateKey];

// If lastRead is nil,App first run: set up user defaults.
if (lastRead == nil)
{
    NSDictionary *appDefaults  = [NSDictionary dictionaryWithObjectsAndKeys:[NSDate date], dateKey, nil];
        
    // do any other initialization you want to do here - e.g. the starting default values.
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"should_play_sounds"];
        
    // sync the defaults to disk
    [[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults];
    [[NSUserDefaults standardUserDefaults] synchronize];
 }

[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:dateKey];


read:
[[NSUserDefaults standardUserDefaults] boolForKey:@"should_play_sounds"];

write:
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"should_play_sounds"];

PS1:
registerDefaults方法不會把defaults存到device裡面。
setobjectforkey方法會自動update到device裡。

PS2:
如果是透過 Xcode 編譯來執行此應用程式時,第一次執行的設定值有可能plist會無法吃到,若要測試應用程式功能是否運作正常請確定您已經「 Stop 」 Xcode 編譯器。(後來發現是跟擺放位置有關)

PS3:
如果你是在模擬器上測試,NSUserDefaults 的資料會被儲存在 /Users/[USERNAME]/Library/Application Support/iPhone Simulator/5.1/Applications/[SIMULATOR_APP_ID]/Library/Preferences/[BUNDLE_ID].plist。

2 comments: