使用NSCoding和NSCoder将对象写入Plist

时间:2014-02-17 19:12:13

标签: ios objective-c nscoding

我创建了一个符合NSCoding

的类
- (id) initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if (self) {
       self.name = [aDecoder decodeObjectForKey:@"name"];
       self.type = [aDecoder decodeObjectForKey:@"type"];
    }
    return self;
}

- (void) encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeObject:self.type forKey:@"type"];
}

然后用于保存和读取plist的方法如下:

- (IBAction)read:(id)sender
{
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:self.plistDocPath];
    //NSLog(@"plist contents: %@",dic);
    NSData *dataObj = [dic objectForKey:@"obj2"];
    NSLog(@"dataObj: %@",dataObj);
    ObjClass *obj = [NSKeyedUnarchiver unarchiveObjectWithData:dataObj];
    NSLog(@"decoded object: %@",obj);
}

- (IBAction)write:(id)sender
{
    ObjClass *obj = [[ObjClass alloc] initWithName:@"nick" andType:@"human"];
    //NSString *str = @"example";
    NSMutableDictionary *dic = [NSMutableDictionary          dictionaryWithContentsOfFile:self.plistDocPath];
    NSString *key = [NSString stringWithFormat:@"obj%i",dic.count];
    NSData *objData = [NSKeyedArchiver archivedDataWithRootObject:obj];
    [dic setObject:objData forKey:key];
    [dic writeToFile:self.plistDocPath atomically:YES];
}

如果我查看文件,我正在看到一个带有字节的键“obj2”的NSData对象,写入进程似乎工作正常。

问题是当我尝试从我正在获取的文件中读取

2014-02-17 20:48:53.780 FileManagerSample[589:70b] *** NSForwarding: warning: object      0x1661f24 of class 'Object' does not implement methodSignatureForSelector: -- trouble ahead
2014-02-17 20:48:53.780 FileManagerSample[589:70b] *** NSForwarding: warning: object 0x1661f24 of class 'Object' does not implement doesNotRecognizeSelector: -- abort

有人可以帮忙,因为我很难过。

0 个答案:

没有答案