[iOS]初期設定NSUserDefaults | Cocoa練習帳

[iOS]初期設定NSUserDefaults

アプリケーションの初期設定の情報は、NSUserDefaultsクラスを使えば実現できる。ただ、単純にNSUserDefaultsを使って値を読み書きするだけだと、扱う情報が増えてくると複雑になってくるので、先日紹介したDocumentクラスを使った実装を紹介する。



自分のアプリケーション用のDocumentクラスを用意する。



@interface Document : NSObject

@property (strong, nonatomic) NSString *message;

- (void)clearDefaults;
- (void)updateDefaults;
- (void)loadDefaults;
@end


初期設定の項目をプロパティとして持ち、読み書き処理をメソッドして用意する。以下が実装例だ。



@implementation Document
@synthesize message = _message;
- (void)clearDefaults
{
if ([[NSUserDefaults standardUserDefaults] objectForKey:@"message"]) {
DBGMSG(@"remove message:%@", self.message);
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"message"];
}
}

- (void)updateDefaults
{
NSString *aMessage = nil;
if ([[NSUserDefaults standardUserDefaults] objectForKey:@"message"]) {
aMessage = [[NSUserDefaults standardUserDefaults] objectForKey:@"message"];
}
if (self.message) {
if ((aMessage) && ([aMessage compare:self.message] == NSOrderedSame)) {
}
else {
[[NSUserDefaults standardUserDefaults] setObject:self.message forKey:@"message"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
}

- (void)loadDefaults
{
if ([[NSUserDefaults standardUserDefaults] objectForKey:@"message"]) {
self.message = [[NSUserDefaults standardUserDefaults] objectForKey:@"message"];
}
}
@end


iOSでは、ユーザに保存という処理を意識させないのが優れたUIの条件のようだ。アプリケーションのデリゲート・クラスでアプリケーションが非アクティブになるタイミングで初期設定の値を保存する。



@implementation AppDelegate
@synthesize window = _window;
@synthesize viewController = _viewController;
@synthesize document = _document;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.document = [[Document alloc] init];
[self.document loadDefaults];

self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
[self.document updateDefaults];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
[self.document updateDefaults];
}
@end


ソースコード
GitHubからどうぞ。

https://github.com/murakami/workbook/tree/master/ios/Defaults - GitHub

関連情報
Data Management Coding How-To's

iOS Developer Libraryの情報です。