在NSMutableDictionary中存储自定义对象
我想在NSMutableDictionary中存储自定义对象。当我从NSMutableDictionary中读取对象时,保存时总是为空。在NSMutableDictionary中存储自定义对象
下面是代码
//保存
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自定义类的对象?
writeToFile
方法只能将标准类型的对象存储到plist中。如果你有自定义对象,你必须使用NSKeyedArchiver
/NSKeyedUnarchiver
。
问题不在于将对象放入字典中;问题在于将它写入文件。
您的自定义班级必须是serializable。您需要实施NSCoding
protocol,以便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.
}
基本上你只是列出你需要保存实例变量,然后读取它们回正常。
更新:如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];
我认为应该这样做。
嗨乔希,我已经实现了NSCoding,仍然无法保存在字典中的对象。正如迈克所说,我检查了写入文件的结果,结果为“否”。任何想法? – Leo 2011-04-11 19:40:10
@Leo:没错,对不起。 Eimantas提到了你需要的另一半:'NSKeyedArchiver'。我已经更新了我的答案以包含该部分。 – 2011-04-11 20:39:56
NSLog输出告诉你什么?你能读取该文件来验证你的对象是否正确写入它? – alesplin 2011-04-11 18:59:06
2011-04-11 19:31:14.386持久性[1757:207] Object(null) 2011-04-11 19:31:14.388持久性[1757:207] property1:(null) – Leo 2011-04-11 19:05:31
' - [NSDictionary writeToFile:原子地:]'返回一个'BOOL'。检查结果是否发生在你身上? – 2011-04-11 19:23:32