1. UISwichを生成する
UISwitch *switchObj = [[UISwitch alloc] initWithFrame:CGRectMake(1.0, 1.0, 20.0, 20.0)];
switchObj.on = [defaults integerForKey:@"hoge"];
[switchObj addTarget:self
action:@selector(hogeSwitch:)
forControlEvents:UIControlEventValueChanged];
cell.accessoryView = switchObj;
[switchObj release];
2. UISwitchの内容をNSUserDefaultsに保存する
- (IBAction)hogeSwitch:(id)sender
{
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
if ([sender isOn] == YES) {
[defaults setInteger:1 forKey:@"hoge"];
} else {
[defaults setInteger:0 forKey:@"hoge"];
}
}
UISwitchのON/OFFの項目は、BOOL値(YES/NO)。
YESは0以外,NOは0なので、NSUserDefaultsに設定するときは setIntegerで、NSUserDefaultsからUISwitchに設定するときは integerForKeyを使う。
初回実行時のときなど、NSUserDefaultsがiPhoneまたはiPhone Simulator上に設定されていないときは、次のようなコードにする。
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
if (![defaults stringForKey:@"hoge"]) { // NSUserDefaults未設定
UISwitch *switchObj = [[UISwitch alloc] initWithFrame:CGRectMake(1.0, 1.0, 20.0, 20.0)];
switchObj.on = NO;
[switchObj addTarget:self
action:@selector(hogeSwitch:)
forControlEvents:UIControlEventValueChanged];
cell.accessoryView = switchObj;
[switchObj release];
} else { // NSUserDefaultsから設定
UISwitch *switchObj = [[UISwitch alloc] initWithFrame:CGRectMake(1.0, 1.0, 20.0, 20.0)];
switchObj.on = [defaults integerForKey:@"hoge"];
[switchObj addTarget:self
action:@selector(hogeSwitch:)
forControlEvents:UIControlEventValueChanged];
cell.accessoryView = switchObj;
[switchObj release];
}
タグ:iPhone
【NSUserDefaultsの最新記事】