【问题标题】:Make a Custom Class Serializable in Objective-c/iPhone?在 Objective-c/iPhone 中使自定义类可序列化?
【发布时间】:2023-03-13 20:35:01
【问题描述】:

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

【问题讨论】:

    标签: iphone objective-c serialization xml-serialization


    【解决方案1】:

    您需要实现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"];
    }
    

    【讨论】:

    • +1 您可能需要调用[super initWithCoder:aDecoder][super encodeWithCoder:encoder],具体取决于您子类化的类。 =)
    • 我有一个关于最佳实践的问题...我应该让类 Serializable 还是让 UI 开发人员在任何所需的输出中序列化它?
    猜你喜欢
    • 2011-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-18
    • 2010-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多