我遇到了 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。我想不出任何帮助,非常感谢!
谢谢