gpt4 book ai didi

ios - NSKeyedArchiver 不保存自定义对象属性

转载 作者:行者123 更新时间:2023-11-28 17:55:18 29 4
gpt4 key购买 nike

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

Album 和 Song 都是 NSObject 固有的,并且符合 NSCoding 协议(protocol)。以下是我如何实现该协议(protocol):

专辑实现文件:

-(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 属性都是 NSString,white songs 属性是一个 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。我无法弄清楚任何帮助,非常感谢!!

谢谢

最佳答案

您实现 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];

然后您可以保存此数据以便稍后取消存档。

关于ios - NSKeyedArchiver 不保存自定义对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10868120/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com