如何使我自己的自定义类可序列化?我特别想把它写到 iPhone 上的一个文件中,只是 plist,你的类只是一个简单的实例类,只是 NSStrings,也许还有一个 NSUrl。
最佳答案
您需要实现 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"];
}
关于iphone - 在 Objective-c/iPhone 中使自定义类可序列化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2182115/