在NSMutableDictionary中存储自定义对象

时间:2011-04-11 18:41:31

标签: objective-c cocoa-touch nsmutabledictionary

我正在尝试在NSMutableDictionary中存储自定义对象。我从NSMutableDictionary读取对象后保存它总是为null。

这是代码

//保存

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中存储自定义类对象?

2 个答案:

答案 0 :(得分:7)

问题不在于将对象放入字典中;问题在于将其写入文件。

您的自定义类必须为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.
}

基本上你只是列出你需要保存的ivars,然后正确阅读它们。

更新:如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];

我认为应该这样做。

答案 1 :(得分:2)

writeToFile方法只能将标准类型的对象存储到plist中。如果您有自定义对象,则必须使用NSKeyedArchiver / NSKeyedUnarchiver