我正在尝试使用NSKeyedArchiver
/NSKeyedUnarchiver
将类属性的数据存储在文件中,以便在应用程序启动之间保持属性的状态。
我在 MyClass.h 中声明了这样的属性:
@property (nonatomic, weak) NSDictionary *myDictionary;
我在 MyClass.m 中创建了自定义 getter 和 setter 方法,以确保将 NSDictionary 写入磁盘:
-(NSDictionary *)myDictionary {
NSDictionary *dictionary;
NSString *path = [self pathToDataStore];
if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
dictionary = [NSDictionary dictionary];
} else {
NSData *archivedData = [NSData dataWithContentsOfFile:path];
dictionary = [NSKeyedUnarchiver unarchiveObjectWithData:archivedData];
}
return dictionary;
}
-(void)setMyDictionary:(NSDictionary *)dictionary {
NSString *path = [self pathToDataStore];
NSDictionary *rootObject = [NSDictionary dictionaryWithDictionary:dictionary];
[NSKeyedArchiver archiveRootObject:rootObject toFile:path];
self.myDictionary = dictionary;
}
这导致调用的无限循环[self setMyDictionary]
,所以很明显我做错了什么。但问题是什么?