NSUserDefaults

やったこと

NSUserDefaultsを使ってみる。

  1. AppDelegateでデータ登録。
  2. ViewControllerでNextViewControllerに画面遷移。
  3. NextViewControllerでデータ表示して別のデータにすげ替える。
  4. NextNextViewControllerですげ替えたデータを表示できることを確認。

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    
    // ここから
    // Override point for customization after application launch.
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary* dictionary = [NSMutableDictionary dictionary];
    [dictionary setObject:@"value1" forKey:@"key1"];
    [dictionary setObject:@"value2" forKey:@"key2"];
    [defaults setObject:dictionary forKey:@"DATA"];
    NSLog(@"データ追加:%@", dictionary);
    // ここまで
    
    
    self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    return YES;
}

ViewController.m

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    NextViewController *next = [[NextViewController alloc] init];
    [self.view addSubview:next.view];
}

NextViewController.m

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary* dictionary = [defaults objectForKey:@"DATA"];
    
    NSLog(@"データ取り出し: %@", dictionary);
    
    dictionary = [NSMutableDictionary dictionary];
    [dictionary setObject:@"next_value1" forKey:@"next_key1"];
    [dictionary setObject:@"next_value2" forKey:@"next_key2"];
    [defaults setObject:dictionary forKey:@"DATA"];
    
    NSLog(@"新規データ追加:%@", dictionary);
    NextNextViewController *nextnext = [[NextNextViewController alloc] init];
    [self.view addSubview:nextnext.view];
    
    
}

NextNextViewController.m

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary* dictionary = [defaults objectForKey:@"DATA"];
    
    NSLog(@"新規データ取り出し: %@", dictionary);
}

結果

2012-03-26 13:58:16.809 RENSYU2[1753:f803] データ追加:{
    key1 = value1;
    key2 = value2;
}
2012-03-26 13:58:16.850 RENSYU2[1753:f803] データ取り出し: {
    key1 = value1;
    key2 = value2;
}
2012-03-26 13:58:16.850 RENSYU2[1753:f803] 新規データ追加:{
    "next_key1" = "next_value1";
    "next_key2" = "next_value2";
}
2012-03-26 13:58:16.852 RENSYU2[1753:f803] 新規データ取り出し: {
    "next_key1" = "next_value1";
    "next_key2" = "next_value2";
}

でも

NSMutableDictionary* dictionary = [defaults objectForKey:@"DATA"];

で取り出した、NSMutableDictionaryにデータをさらに追加しようとすると落ちる........