在 Objective-c/iPhone 中使自定义类可序列化? [英] Make a Custom Class Serializable in Objective-c/iPhone?

查看:28
本文介绍了在 Objective-c/iPhone 中使自定义类可序列化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使我自己的自定义类可序列化?我特别想把它写到 iPhone 上的一个文件中,只是 plist 和你的类只是一个简单的实例类,只是 NSStrings 可能还有一个 NSUrl.

How can I make my own custom class serializable? I specifically want to write it to a file on iPhone, just plist and thee class is just a simple instance class, just NSStrings and maybe a NSUrl.

推荐答案

您需要实施 NSCoding 协议.实现 initWithCoder: 和 encodeWithCoder:,您的自定义类将与 NSKeyedArchiver 和 NSKeyedUnarchiver 一起使用.

You'll want to implement the NSCoding protocol. Implement initWithCoder: and encodeWithCoder: and your custom class will work with NSKeyedArchiver and NSKeyedUnarchiver.

你的 initWithCoder: 应该是这样的:

Your initWithCoder: should look like this:

- (id)initWithCoder:(NSCoder *)aDecoder
{
   if(self = [super init]) // this needs to be [super initWithCoder:aDecoder] if the superclass implements NSCoding
   {
      aString = [[aDecoder decodeObjectForKey:@"aString"] retain];
      anotherString = [[aDecoder decodeObjectForKey:@"anotherString"] retain];
   }
   return self;
}

和 encodeWithCoder:

and encodeWithCoder:

- (void)encodeWithCoder:(NSCoder *)encoder
{
   // add [super encodeWithCoder:encoder] if the superclass implements NSCoding
   [encoder encodeObject:aString forKey:@"aString"];
   [encoder encodeObject:anotherString forKey:@"anotherString"];
}

这篇关于在 Objective-c/iPhone 中使自定义类可序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆