0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

UserDefaultsを使った永続化について(保存されない場合がある)

Last updated at Posted at 2020-07-06

iOS12.4.1
iPhone7で確認
最小限のプログラムでテストしたわけではないのでプログラム自体のバグの可能性もあり

以下のようなプログラムでUserDefaultsを使って保存した場合、isSaveがYESになっていて、再読み込みしてUserDefaultsに保存した値が変更されたことを確認したあとにXcodeでプログラムをストップして再起動させた際にデータが永続化されていないことがありました。

呼び出し側

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    [dataStore saveDatas]; // UserDefaultsで保存処理
}

保存処理

    // 保存処理
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    
    //NSDataに変換する
    NSData* baseDataData = [NSKeyedArchiver archivedDataWithRootObject:baseData];

    BOOL isSave = [defaults synchronize];
    NSLog(@"isSave:%d", isSave);

UserDefaultsの変更はメモリ上にキャッシュされていて実際に永続化(ディスクに書き込み)されるかどうかはシステム判断のようです。synchronize()を呼んだとしても同期されず永続化されていませんでした。
UserDefaultsを使った保存はお手軽ですが、本当に消えたら困るデータには使わないほうがいいのかもしれません。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?