2

我遇到了 NSKeyedArchiver 的问题。我正在尝试存档一个字典,该字典又包含自定义对象、专辑和歌曲的数组。

Album 和 Song 都是 NSObject 固有的,并且符合 NSCoding 协议。这是我实现协议的方式:

相册实现文件:

-(id)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];

    self.title = [aDecoder decodeObjectForKey:@"title"];
    self.artistName = [aDecoder decodeObjectForKey:@"artistName"];
    self.songs = [aDecoder decodeObjectForKey:@"songs"];

    return self;
}

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

歌曲实现文件:

-(id)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];
    self.title = [aDecoder decodeObjectForKey:@"title"];
    self.artistName = [aDecoder decodeObjectForKey:@"artistName"];

    return self;
}

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

title 和 artistName 属性都是 NSStrings,白色的 song 属性是 Song 对象的数组。

我将这些对象的数组放入名为 ipodDictForArchiving 的字典中,然后像这样归档字典:

-(NSData *)dataForClient {
    NSMutableData *data = [[NSMutableData alloc] init];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [archiver encodeObject:[self ipodDictForArchiving] forKey:kDataArchive];
    [archiver finishEncoding];
    NSLog(@"encoded dictionary");
    return data;
}

然后我像这样解压缩字典:

-(NSDictionary *)unarchiveData:(NSData *)data {
    NSData *clientData = data;
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:clientData];
    NSDictionary *myDictionary = [unarchiver decodeObjectForKey:kDataArchive];
    [unarchiver finishDecoding];

    return myDictionary;
}

出于某种原因,字典包含 Song 和 Album 对象,但这些对象的属性返回 null。我想不出任何帮助,非常感谢!

谢谢

4

1 回答 1

-1

您实现 initWithCoder 的方式不正确,应该如下:

- (id)initWithCoder:(NSCoder *)aDecoder {

    Album *al = [[Album alloc] init];

    al.title = [[[NSString alloc] initWithString:[aDecoder decodeObjectForKey:@"title"]] autorelease];
    al.artistName = [[[NSString alloc] init] initWithString:[aDecoder decodeObjectForKey:@"artistName"]] autorelease];
    al.songs = [[[NSArray alloc] initWithArray:[aDecoder decodeObjectForKey:@"songs"]] autorelease];

    return al;
}

宋也是一样。

[编辑] 而且您存档相册的方式似乎不正确,让我们尝试一种更简单的方式:

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:album];

然后,您可以保存此数据以在以后取消归档。

于 2012-06-03T05:55:31.033 回答