【发布时间】:2011-04-11 18:41:31
【问题描述】:
我正在尝试将自定义对象存储在 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 中存储自定义类对象?
【问题讨论】:
-
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:atomically:]返回一个BOOL。你有没有想过检查结果?
标签: objective-c cocoa-touch nsmutabledictionary