1

NSDate値をアプリケーションのplistファイルに保存する方法を理解しようとしています。

私は現在これを行っていますが、それを保存しなければならない実際の部分で立ち往生しています。

NSString *datePlistPath = [[NSBundle mainBundle] pathForResource: @"my-Date" ofType: @"plist"];
        NSMutableDictionary *dict = [NSDictionary dictionaryWithContentsOfFile: datePlistPath];

        // to be saved to plist
        NSDate *date = [NSDate date];

// this is where I start to get abit lost, I want to set the date to the right plist value then commit the changes
        [dict setObject:date forKey:@"my-Date"];
        [dict writeToFile:datePlistPath atomically:YES]; // error happening here.

助けていただければ幸いです

更新:コードの最後の行に到達すると、これが生成されるエラーです...

*キャッチされなかった例外'NSInternalInconsistencyException'が原因でアプリを終了しています、理由:'-[__ NSCFDictionary setObject:forKey:]:変更メソッドが不変オブジェクトに送信されました'

4

5 に答える 5

3

NSMutableDictionarydictionaryWithContentsOfFileを使用する

NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile: datePlistPath];

NSDictionary dictionaryWithContentsOfFileを使用する場合、NSMutableDictionaryではなくNSDictionaryを提供します。

また、アプリケーションバンドルのplistを更新することはできず、代わりにドキュメントディレクトリに保存します。

dit-objects-in-array-from-plistリンクを参照してください

于 2012-09-19T04:02:08.123 に答える
1

あなたの場合の解決策は次のように単純だと思います

交換

NSMutableDictionary *dict = [NSDictionary dictionaryWithContentsOfFile: datePlistPath];

NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile: datePlistPath];
于 2012-09-19T03:55:27.033 に答える
1
NSMutableDictionary *dict = [NSDictionary dictionaryWithContentsOfFile: datePlistPath];

に置き換えNSDictionaryますNSMutableDictionary

于 2012-09-19T04:20:15.617 に答える
0

にファイルを書き込むことはできません

NSBundle

。ファイルは、Documentsディレクトリ、tempディレクトリ、およびいくつかの事前定義された場所にのみ保存できます。次のコードを試すことができます。それは私にとってはうまくいきました。

NSArray * path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory、NSUserDomainMask、YES);

NSString * filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@ "file.plist"];

NSDate *currentDate = [NSDate date];
NSMutableDictionary *d = [NSMutableDictionary new];
[d setObject:currentDate forKey:@"my-date"];

[d writeToFile:filePath atomically:YES];
于 2012-09-19T04:14:03.260 に答える
0

独自のバンドル内のファイルに書き込むことはできません。日付を何に使用しているのか正確にはわかりませんが、これNSDateを起動間も維持したい場合は、おそらくこの日付をに書き込みますNSUserDefaults

ここのドキュメント: https ://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/

それを書くためのあなたのコードは次のようになります:

[[NSUserDefaults standardUserDefaults] setObject:date forKey:@"my-Date"];

そしてそれを読み返すためにあなたはするでしょう

NSDate* myDate = (NSDate*)[[NSUserDefaults standardUserDefaults] objectForKey:@"my-Date"];
// Be prepared for a nil value if this has never been set.
于 2015-12-21T21:07:35.437 に答える