在 NSMutableDictionary 中存储自定义对象
我正在尝试在 NSMutableDictionary 中存储自定义对象。保存后,当我从 NSMutableDictionary 读取对象时,它始终为空。
这是代码
//Saving
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];
// Reading
NSString *filePath = [self dataFilePath];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
CustomObject *tempObj = [dict objectForKey:@"FirstObjectKey"];
NSLog(@"Object %@", tempObj);
NSLog(@"property1:%@,,tempObj.property1);
如何在 NSMutableDictionary 中存储自定义类对象?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题不在于将对象放入字典中;而在于将对象放入字典中。问题在于将其写入文件。
您的自定义类必须是 可序列化。您需要实现 < code>NSCoding 协议,以便当您要求将类写入磁盘时,Cocoa 知道如何处理您的类。
这很简单;您需要实现两种如下所示的方法:
本质上您只是列出需要保存的 ivars,然后正确地读回它们。
更新:正如 Eimantas 提到的,您还需要
NSKeyedArchiver
。保存:重新加载:
我认为应该这样做。
The problem is not with putting the object into the dictionary; the problem is with writing it to a file.
Your custom class has to be serializable. You need to implement the
NSCoding
protocol so that Cocoa knows what to do with your class when you ask for it to be written out to disk.This is pretty simple to do; you need to implement two methods that will look something like the following:
Essentially you're just listing the ivars that you need to save, and then reading them back in properly.
UPDATE: As mentioned by Eimantas, you'll also need
NSKeyedArchiver
. To save:To reload:
I think that should do it.
writeToFile
方法只能将标准类型的对象存储到 plist 中。如果您有自定义对象,则必须使用NSKeyedArchiver
/NSKeyedUnarchiver
来实现此目的。writeToFile
method can store only standard types of objects into plist. If you have custom object you'd have to useNSKeyedArchiver
/NSKeyedUnarchiver
for this.