#define kProtocol @"protocol" #define kSlider @"slider" #define kUserName @"userName" #define kVersion @"version" #define kSwitch @"switch" //用來取得Settings.Bundle各物件的預設值 -(NSDictionary*)settingsBundleDefaultValues { NSMutableDictionary *defaultDic_ = [[NSMutableDictionary alloc]init]; NSURL *settingsUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Root" ofType:@"plist" inDirectory:@"Settings.bundle"] isDirectory:YES]; NSDictionary *settingBundle = [NSDictionary dictionaryWithContentsOfURL:settingsUrl]; NSArray *preference_ = [settingBundle objectForKey:@"PreferenceSpecifiers"]; for (NSDictionary *component_ in preference_) { NSString *key = [component_ objectForKey:@"Key"]; NSString *defaultValue = [component_ objectForKey:@"DefaultValue"]; if (!key||!defaultValue) continue; if (![component_ objectForKey:key]) { [defaultDic_ setObject:[component_ objectForKey:@"DefaultValue"] forKey:key]; } } return defaultDic_; } //讀取 - (IBAction)buttonLoad:(id)sender { /* [protocol setTitle:@"SMTP" forSegmentAtIndex:0]; [protocol setTitle:@"HTTP" forSegmentAtIndex:1]; [protocol setTitle:@"IMAP" forSegmentAtIndex:2]; [protocol setTitle:@"POP3" forSegmentAtIndex:3]; */ NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults]; /* 在執行App之前必須進到"設定"去,去設定App的值 連settings.bundle內對各物件進行設定預設值也沒有辦法一開始就直接被讀取 所以要對NSUserDefault的Key註冊預設值,值的來源是Settings.Bundle的DefaultValue */ [userDefault registerDefaults:[self settingsBundleDefaultValues]]; NSArray *arrProtocol = [NSArray arrayWithObjects:@"SMTP",@"HTTP",@"IMAP",@"POP3", nil]; [protocol setSelectedSegmentIndex:[arrProtocol indexOfObject:[userDefault stringForKey:kProtocol]]]; txtVersion.text = [userDefault stringForKey:kVersion]; [mySwitch setOn:[userDefault boolForKey:kSwitch] animated:YES]; [slider setValue: [userDefault floatForKey:kSlider]]; } //儲存 - (IBAction)buttonSave:(id)sender { NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults]; NSArray *arrProtocol = [NSArray arrayWithObjects:@"SMTP",@"HTTP",@"IMAP",@"POP3", nil]; [userDefault setObject:[arrProtocol objectAtIndex:protocol.selectedSegmentIndex] forKey:kProtocol]; [userDefault setObject:txtVersion.text forKey:kVersion]; [userDefault setBool:mySwitch.on forKey:kSwitch]; [userDefault setFloat:slider.value forKey:kSlider]; } |