【发布时间】:2023-03-13 20:35:01
【问题描述】:
如何使我自己的自定义类可序列化?我特别想把它写到 iPhone 上的一个文件中,只是 plist,而你的类只是一个简单的实例类,只是 NSStrings,也许还有一个 NSUrl。
【问题讨论】:
标签: iphone objective-c serialization xml-serialization
如何使我自己的自定义类可序列化?我特别想把它写到 iPhone 上的一个文件中,只是 plist,而你的类只是一个简单的实例类,只是 NSStrings,也许还有一个 NSUrl。
【问题讨论】:
标签: iphone objective-c serialization xml-serialization
您需要实现NSCoding protocol。实现 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"];
}
【讨论】:
[super initWithCoder:aDecoder] 或[super encodeWithCoder:encoder],具体取决于您子类化的类。 =)