当原始类不可用时,如何解码对象? [英] How can I decode an object when original class is not available?

查看:84
本文介绍了当原始类不可用时,如何解码对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个iOS 7应用程序,该应用程序将自定义对象作为文件保存到应用程序的iCloud Docs文件夹中.为此,我使用了NSCoding协议.

I have an iOS 7 application that saves a custom object to app's iCloud Docs folder as a file. For this, I make use of NSCoding protocol.

@interface Person : NSObject <NSCoding>

    @property (copy, nonatomic) NSString *name
    @property (copy, nonatomic) NSString *lastName

@end

对象序列化在iOS 7版本的应用程序中完美运行:

Object serialization works perfectly in iOS 7 version of the app:

  1. initWithCoderencodeWithCoder

[NSKeyedArchiver archivedDataWithRootObject:person]

person = NSKeyedUnarchiver unarchiveObjectWithData:(NSData *)theData]

但是我需要将此应用程序移至iOS 8,并且此类将以该新iOS 8版本的应用程序快速编码并重命名".

But I need to move this app to iOS 8, and this class will be coded in swift and 'renamed' for this new iOS 8 version of the app.

class PersonOldVersion: NSObject, NSCoding {
    var name = ""
    var lastName = ""
}

当我尝试取消归档对象时,出现以下错误:

When I try to unarchive the object I got the following error:

*** Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason: '*** -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (Person)'

我已经尝试将快速类'PersonOldVersion'重命名为原始类名('Person'),但仍然失败.

I already tried renaming swift class 'PersonOldVersion' to original class name ('Person') but still fails.

如何解码原始类不可用的对象?

How can I decode an object which original class isn't available?

推荐答案

如果Objective-C中类的名称很重要,则需要显式指定名称.否则,Swift将提供一些错误的名称.

If the name of the class in Objective-C is important, you need to explicitly specify the name. Otherwise, Swift will provide some mangled name.

@objc(Person)
class PersonOldVersion: NSObject, NSCoding {
    var name = ""
    var lastName = ""
}

这篇关于当原始类不可用时,如何解码对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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