仅将 NSDictionary 放在单例中不会在应用程序启动之间保留它,您需要将其保存到磁盘,然后在应用程序启动时从磁盘中读取它。
如果您在 NSDictionary 或 NSArrays 中或根本没有自定义对象(您创建的子类),则可以使用此方法保存 NSDictionary 为:
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag
并从磁盘打开字典:
- (id)initWithContentsOfFile:(NSString *)path
但是,如果您确实有自定义对象,它们将需要符合 NSCoding 协议。您必须使用 2 种不同的方法来保存和打开它:
NSCoding 是一个协议,所以在你的 header 中你需要将它添加到 interface 行的末尾:
@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"];
}
您需要为要存储的每个值(通常是您的类所具有的所有属性、[和实例变量])设置相似的行。请注意float 行与其他行的不同之处。
键可以是您想要的任何字符串,只要每个属性都有自己的唯一键并且它们在两种方法之间匹配即可。我个人使用属性的名称,因为它更容易理解。
当你真正想保存你使用的 NSDictionary 时:
[NSKeyedArchiver archiveRootObject:myDictionary toFile:pathToMyDictionary];
然后打开字典:
NSDictionary *myDictionary = [NSKeyedUnarchiver unarchiveObjectWithFile:pathToMyDictionary];
(根据您的代码,您可能需要retainmyDictionary)
要获取字典的路径(用于保存和打开),请执行以下操作:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pathToMyDictionary = [documentsDirectory stringByAppendingPathComponent:@"myDictionary.dat"];
希望对您有所帮助,如果您对此答案有任何疑问,请发表评论:)