NSData on custom class?

久未见 提交于 2019-12-01 09:34:53

It sounds like you're really just asking how to implement -encodeWithCoder: and -initWithCoder:. It's pretty straightforward:

-(void) encodeWithCoder:(NSCoder *)encoder
{
    [encoder encodeObject:characterImage forKey:@"character image"];
    [encoder encodeInt:health forKey:@"health"];
    [encoder encodeObject:name forKey:@"name"];
}

That's all. -initWithCoder: works exactly the same way, except you call the complementary methods, such as: characterImage = [decoder decodeObjectForKey:@"character image"];.

If you need to provide the data in a particular format to work with the target device that doesn't support the archive format, you can do that instead and use the -encodeBytes:length:forKey: method to store whatever you like, or write data in your own format into a NSMutableData object and then use -encodeObject:forKey: on that. Your target device may still need to find your data in whatever envelope the encoder stores it; you can make that easier by starting with a known series of bytes. I'm not sure whether that's necessary in your case, but it's something to keep in mind.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!