在NSMutableDictionary中存储自定义对象

Leo*_*Leo 2 cocoa-touch objective-c 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];
Run Code Online (Sandbox Code Playgroud)

// 读

 NSString *filePath = [self dataFilePath];
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];

        CustomObject *tempObj = [dict objectForKey:@"FirstObjectKey"];

        NSLog(@"Object %@", tempObj);
        NSLog(@"property1:%@,,tempObj.property1);
Run Code Online (Sandbox Code Playgroud)

如何在NSMutableDictionary中存储自定义类对象?

Jos*_*ell 7

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

您的自定义类必须是可序列化的.您需要实现NSCoding协议,以便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.
}
Run Code Online (Sandbox Code Playgroud)

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

更新:如Eimantas所述,您还需要NSKeyedArchiver.要保存:

NSData * myData = [NSKeyedArchiver archivedDataWithRootObject:myDict];
BOOL result = [myData writeToFile:[self dataFilePath] atomically:YES];
Run Code Online (Sandbox Code Playgroud)

要重新加载:

NSData * myData = [NSData dataWithContentsOfFile:[self dataFilePath]];
NSDictionary * myDict = [NSKeyedUnarchiver unarchiveObjectWithData:myData];
Run Code Online (Sandbox Code Playgroud)

我认为应该这样做.