我遇到了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对象的数组。
我将这些对象的数组放入一个名为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。我无法想出任何帮助,非常感谢!!
由于
答案 0 :(得分:-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];
然后您可以保存此数据以便以后取消归档。