NSUserDefaults を使って設定を保持する | 静岡県富士市在住のiPhoneアプリ開発者ブログ

NSUserDefaults を使って設定を保持する

アプリケーション固有の設定値を保持するには、NSUserDefaults を使う

インスタンスの取得
[NSUserDefaults standardUserDefaults];

設定の書き込み
- (void)setObject:(id)value forKey:(NSString *)defaultName;
- (void)setInteger:(NSInteger)value forKey:(NSString *)defaultName;
など

設定の読み込み
- (NSString *)stringForKey:(NSString *)defaultName;
- (NSInteger)integerForKey:(NSString *)defaultName;
など

Key を設定して値を書き込む、読み込み時はKey を指定する



#define cKey_animation @"animation"

//初期化時にintegerForKey で値を取得し、クラスのフィールドNSInteger animation に保持
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
if (self != nil)
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
animation = [defaults integerForKey:cKey_animation];
}
}
return self;
}

//スイッチのON/OFF の切り替え時に setInteger で値を書き込む
- (void)setswtAnimation:(id)sender
{
if ([sender isOn])
animation = 1;
else
animation = 0;

[[NSUserDefaults standardUserDefaults] setInteger:animation forKey:cKey_animation];
}