繁体   English   中英

在Objective-c / iPhone中创建自定义类可序列化?

[英]Make a Custom Class Serializable in Objective-c/iPhone?

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

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

你的initWithCoder:应该是这样的:

- (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:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM