本文介绍了添加了自定义框架,现在Swift无法取消存档数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的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 as public so they'd be visible outside of the framework
  • Add import DemoSharedCode to any classes that want to use DemoNote

因此,编译器现在很高兴.但是在运行时,取消归档失败并显示以下错误:

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无法取消存档数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 13:07