存档NSString字典

时间:2012-08-27 05:39:54

标签: cocoa

我想归档一个只包含NSStrings的字典,但是当我取消归档时,发生了错误:

  

[NSKeyedUnarchiver initForReadingWithData:]:NSKeyedUnarchiver无法解码非键控存档

我的代码是:

- (IBAction)startArchive:(id)sender {
    NSString *path = [self pathForDataFile];
    NSMutableDictionary *ageDictionary= [NSMutableDictionary dictionary];
    [ageDictionary setValue:@"12" forKey:@"Jack"];
    [ageDictionary setValue:@"22" forKey:@"John"];
    [NSArchiver archiveRootObject:ageDictionary toFile:path];
}


- (IBAction)unarchive:(id)sender {
    NSString *path = [self pathForDataFile];
    NSDictionary *rootObject = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    NSLog(@"%@",rootObject);
}

2 个答案:

答案 0 :(得分:3)

原因是Unarchiver。您使用NSArchiver进行归档。作为unarchiver你应该使用NSUnarchiver。如果您使用NSKeyedArchiver,则应使用NSKeyedUnarchiver。

你很困惑。

流动代码是测试工作:

    #import <Foundation/Foundation.h>

void startArchive() {
    NSString *path = @"/Users/dinosaur/Desktop/test.plist";
    NSMutableDictionary *ageDictionary= [NSMutableDictionary dictionary];
    [ageDictionary setValue:@"12" forKey:@"Jack"];
    [ageDictionary setValue:@"22" forKey:@"John"];
    [NSArchiver archiveRootObject:ageDictionary toFile:path];
}


void unarchive() {
    NSString *path = @"/Users/dinosaur/Desktop/test.plist";
    NSDictionary *rootObject = [NSUnarchiver unarchiveObjectWithFile:path];
    NSLog(@"%@",rootObject);
}


int main(int argc, char *argv[]) {
    @autoreleasepool {
        startArchive();
        unarchive();
    }
}

=============

这是日志:

2012-08-27 14:03:11.511无标题[7930:707] {     杰克= 12;     约翰= 22; }

答案 1 :(得分:1)

您可以利用NSDictionary(以及类似的'plist'类)中对plists的“深度”支持。查看writeToFile:atomically:dictionaryWithContentsOfFile:,其中(在一行中!)为您创建一个plist文件,并将一个plist读入NSDictionary;只要所有内容都是“plist对象”(NSStrings,NSArrays,NSNumbers等)。