只有在单例中使用NSDictionary不会让它在应用程序启动之间保持不变,您需要将它保存到磁盘,然后在应用程序启动时从磁盘读取它。
如果没有自定义对象中的NSDictionary(您创建的子类),或在NSArrays或非可言,你可以用这个方法来保存的NSDictionary是:
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag
并打开字典从磁盘:
- (id)initWithContentsOfFile:(NSString *)path
但是如果你有自定义对象他们将需要符合NSCoding协议。你将不得不使用2层不同的方法来保存和打开它:
NSCoding是一个协议,所以在你的头,你需要添加它的接口线的末端:
@interface myClassName : NSObject <NSCoding> {
(你应该补充的唯一事情是<NSCoding>
)
然后在你实现你的子类中,你需要添加下面的方法:
- (id)initWithCoder:(NSCoder *)decoder
和:
- (void)encodeWithCoder:(NSCoder *)encoder
当你想解除封存(/开)您的NSDictionary(其中某处包含这个类)的initWithCoder:
方法被调用
encodeWithCoder:
就是被称为当你的NSDictionary被归档(/保存)。 你不要自己调用这些。您需要在其中添加代码:
- (id)initWithCoder:(NSCoder *)decoder {
if ((self = [super initWithCoder:decoder])) {
aProperty = [[decoder decodeObjectForKey:@"aProperty"] retain];
anotherProperty = [[decoder decodeObjectForKey:@"anotherProperty"] retain];
aFloat = [decoder decodeFloatForKey:@"aFloat"];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder {
[super encodeWithCoder:encoder];
[encoder encodeObject:aProperty forKey:@"aProperty"];
[encoder encodeObject:anotherProperty forKey:@"anotherProperty"];
[encoder encodeFloat:aFloat forKey:@"aFloat"];
}
你需要对你想存储(通常所有属性,[和实例变量]你的类有)每个值类似的路线。请注意0系列与其他系列的不同之处。
只要每个属性都有自己的唯一键并且它们在两个方法之间匹配,键可以是任何您想要的字符串。我个人使用财产的名称,因为它更容易理解。
当你真正要保存的NSDictionary使用:
[NSKeyedArchiver archiveRootObject:myDictionary toFile:pathToMyDictionary];
,并打开词典:
NSDictionary *myDictionary = [NSKeyedUnarchiver unarchiveObjectWithFile:pathToMyDictionary];
(取决于你的代码,你可能需要retain
myDictionary
)
要获得路径到您的字典(用于保存和打开),这样做:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pathToMyDictionary = [documentsDirectory stringByAppendingPathComponent:@"myDictionary.dat"];
希望帮助,如果您对此回答任何问题,只是评论:)
什么是NSCoding协议? – aherlambang 2011-03-27 01:43:43
NSCoding协议需要两种方法,一种是对类的属性进行编码,另一种是对属性进行解码。我会编辑我的答案。 – 2011-03-27 10:36:42
一个问题..你有pathToMyDictionary ..例如,该路径应该在哪里? – aherlambang 2011-03-28 23:09:22