Objective c 在NSMutableDictionary中存储自定义对象
我正在尝试在NSMutableDictionary中存储自定义对象。保存后,当我从NSMutableDictionary读取对象时,它总是空的 这是密码 //拯救Objective c 在NSMutableDictionary中存储自定义对象,objective-c,cocoa-touch,nsmutabledictionary,Objective C,Cocoa Touch,Nsmutabledictionary,我正在尝试在NSMutableDictionary中存储自定义对象。保存后,当我从NSMutableDictionary读取对象时,它总是空的 这是密码 //拯救 NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; CustomObject *obj1 = [[CustomObject alloc] init]; obj1.property1 = @"My First Property"; [dict setObje
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
CustomObject *obj1 = [[CustomObject alloc] init];
obj1.property1 = @"My First Property";
[dict setObject:obj1 forKey:@"FirstObjectKey"];
[dict writeToFile:[self dataFilePath] atomically:YES];
//阅读
NSString *filePath = [self dataFilePath];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
CustomObject *tempObj = [dict objectForKey:@"FirstObjectKey"];
NSLog(@"Object %@", tempObj);
NSLog(@"property1:%@,,tempObj.property1);
如何在NSMutableDictionary中存储自定义类对象?问题不在于将对象放入字典;问题在于将其写入文件 您的自定义类必须是。您需要实现,以便当您请求将类写入磁盘时,Cocoa知道如何处理该类 这很简单;您需要实现以下两种方法:
- (id)initWithCoder:(NSCoder *)coder {
self = [super init];
// If inheriting from a class that implements initWithCoder:
// self = [super initWithCoder:coder];
myFirstIvar = [[coder decodeObjectForKey:@"myFirstIvar] retain];
mySecondIvar = [[coder decodeObjectForKey:@"mySecondIvar] retain];
// etc.
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
// If inheriting from a class that implements encodeWithCoder:
// [super encodeWithCoder:coder];
[coder encodeObject:myFirstIvar forKey:@"myFirstIvar"];
[coder encodeObject:mySecondIvar forKey:@"mySecondIvar"];
// etc.
}
基本上,您只是列出了需要保存的IVAR,然后将它们正确地读入
更新:正如Eimantas所提到的,您还需要NSKeyedArchiver
。要保存:
NSData * myData = [NSKeyedArchiver archivedDataWithRootObject:myDict];
BOOL result = [myData writeToFile:[self dataFilePath] atomically:YES];
要重新加载:
NSData * myData = [NSData dataWithContentsOfFile:[self dataFilePath]];
NSDictionary * myDict = [NSKeyedUnarchiver unarchiveObjectWithData:myData];
我认为应该这样做。writeToFile方法只能将标准类型的对象存储到plist中。如果您有自定义对象,则必须为此使用
NSKeyedArchiver
/NSKeyedUnarchiver
。NSLog输出告诉您什么?您可以读取该文件以验证您的对象是否正确写入其中吗?2011-04-11 19:31:14.386 Persistence[1757:207]object(null)2011-04-11 19:31:14.388 Persistence[1757:207]property1:(null)-[NSDictionary writeToFile:atomicaly:
返回一个BOOL
。你有没有想过检查结果?嗨,Josh,我已经实现了NSCoding,但仍然无法将对象保存在字典中。正如Mike提到的,我检查了写入文件的结果,结果是“否”。利奥:是的,对不起;艾曼塔斯提到了你需要的另一半:NSKeyedArchiver
。我已经更新了我的答案以包含这一部分。嗨,艾曼塔斯,我已经实现了NSKeyedArchiver方法,现在我可以保存自定义对象了。我的问题是我能用这本字典吗。我的意思是,在NSDictionary中,有一个内置的函数可以获取所有的密钥,这样您就可以通过它进行加密。我也可以通过归档对象进行枚举吗?除非您将字典与您的对象一起归档(即使用encodeWithCoder而不是WriteFile),否则不会。