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:]: mutating method sent to immutable object”

4

5 回答 5

3

使用NSMutableDictionary dictionaryWithContentsOfFile

NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile: datePlistPath];

如果你使用NSDictionary dictionaryWithContentsOfFile提供你 NSDictionary不是 NSMutableDictionary

此外,您不能更新应用程序包中的 plist,而是存储在文档目录中。

请参阅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];

替换NSDictionaryNSMutableDictionary.

于 2012-09-19T04:20:15.617 回答
0

您不能将文件写入

NSBundle

. 文件只能存储在 Documents 目录、temp 目录和一些预定义的位置。你可以试试下面的代码。它对我来说很好。

NSArray *paths = 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 回答