问题描述
我有一个非常简单的Swift应用程序,其中有一个名为DemoNote
的模型类. DemoNote
实例数组通过键控归档进行读写.当DemoNote
包含在应用程序中时,此方法工作正常.
I have a pretty trivial Swift app that has a model class named DemoNote
. An array of DemoNote
instances is read/written via keyed archiving. This worked fine while DemoNote
was included in the app.
但是后来我将DemoNote.swift
移到了一个名为DemoSharedCode
的新自定义框架.除了确保Xcode在应用程序目标中使用框架之外,我还确保
But then I moved DemoNote.swift
to a new custom framework called DemoSharedCode
. Aside from making sure Xcode was using the framework in the app target, I made sure to
- 将
DemoNote
及其变量和方法标记为public
,以便它们在框架之外可见 - 将
import DemoSharedCode
添加到要使用DemoNote
的任何类中
- Mark
DemoNote
and its vars and methods aspublic
so they'd be visible outside of the framework - Add
import DemoSharedCode
to any classes that want to useDemoNote
因此,编译器现在很高兴.但是在运行时,取消归档失败并显示以下错误:
So now the compiler is happy. But at run time the unarchiving fails with this error:
2015-02-17 12:12:53.417 DemoNotesSwift[70800:16504104] *** Terminating app due to
uncaught exception 'NSInvalidUnarchiveOperationException', reason:
'*** -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class
(DemoNotesSwift.DemoNote)'
在上面,DemoNotesSwift
是应用程序名称,DemoNote
是类名称,并且代码行试图从NSData
blob解压缩对象:
In the above, DemoNotesSwift
is the app name, DemoNote
is the class name, and the line of code is attempting to unarchive objects from an NSData
blob:
let savedObjects = NSKeyedUnarchiver.unarchiveObjectWithData(savedData) as? [(DemoNote)]
我猜想将DemoNote
移至框架意味着其模块名称已更改,这破坏了取消存档的功能,但我不确定.我也不确定该怎么做-也许我需要在解存档器上调用+setClass:forClassName:
,但是如果是这样,我不知道参数是什么.
I'm guessing that moving DemoNote
to the framework means its module name has changed, which breaks unarchiving, but I'm not sure of that. I'm also not sure what to do about it-- maybe I need to call +setClass:forClassName:
on the unarchiver, but if so I don't know what the arguments would be.
推荐答案
将DemoNote
从应用程序移动到框架中确实更改了模块名称,这意味着NSKeyedUnarchiver
由于以下原因无法找到存档类的实例:名称不匹配.解决方法是在取消存档之前添加此行:
Moving DemoNote
from the app to a framework did change the module name, which meant that NSKeyedUnarchiver
couldn't find instances of the archived class due to a name mismatch. The fix was to add this line before unarchiving:
NSKeyedUnarchiver.setClass(DemoNote.self, forClassName: "DemoNotesSwift.DemoNote")
在这种情况下,DemoNote.self
获取当前的完整类名,而DemoNotesSwift.DemoNote
是该类作为应用程序的一部分时曾经被调用的类.
In this case, DemoNote.self
gets the current full class name, and DemoNotesSwift.DemoNote
is what the class used to be called when it was part of the app.
这仅是必要的,因为我以前想要保留现有的数据.
This was only necessary because I had previously existing data that I wanted to keep.
这篇关于添加了自定义框架,现在Swift无法取消存档数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!