1

在应用程序和 iMessage Extension 之间共享结构数组时,我遇到了一个奇怪的问题。

这是我的代码。

struct RecentlyUsed {
    var isPreset: Bool?
    var imgId: Int?
}

extension RecentlyUsed {
    init?(data: NSData) {
        if let coding = NSKeyedUnarchiver.unarchiveObject(with: data as Data) as? Encoding {
            isPreset = coding.isPreset! as Bool
            imgId = coding.imgId!
        }
    }
    func encode() -> NSData {
        return NSKeyedArchiver.archivedData(withRootObject: Encoding(self)) as NSData
    }
    private class Encoding: NSObject, NSCoding {
        let isPreset: Bool?
        let imgId: Int?
        init(_ recentlyUsed: RecentlyUsed) {
            self.isPreset = recentlyUsed.isPreset
            self.imgId = recentlyUsed.imgId
        }
        @objc required init?(coder aDecoder: NSCoder) {
            self.isPreset = aDecoder.decodeObject(forKey: "isPreset") as? Bool
            self.imgId = aDecoder.decodeObject(forKey: "imgId") as? Int
        }
        @objc func encode(with aCoder: NSCoder) {
            aCoder.encode(isPreset, forKey: "isPreset")
            aCoder.encode(imgId, forKey: "imgId")
        }
    }
}

我创建了一个名为“group.io.interepid.sharingdata”的应用程序组来共享这个数组,然后在我的应用程序中进行读写测试。

所以它工作得很好。

var recentlyUsedArr: [RecentlyUsed] = []
...
// Code for read
let settings = UserDefaults(suiteName: "group.io.interepid.sharingdata")
        if let dataArray = settings?.object(forKey: "data") as? [NSData] {
            self.recentlyUsedArr.append(contentsOf: dataArray.map{ RecentlyUsed(data: $0)! })
        } else {

        }
// Code for write
let settings = UserDefaults(suiteName: "group.io.interepid.sharingdata")
                let placeData = self.recentlyUsedArr.map{ $0.encode() }
                settings?.set(placeData, forKey: "data")
                settings?.synchronize()

但是当我在这个应用的 iMessage 扩展中读取数组时,我得到了一个错误。

我在应用程序端使用了相同的代码。

2017-02-14 10:02:59.648256 Emoji Me[5616:2399759] * Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException' , reason: '* -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (_TtCV7emojime12RecentlyUsedP33_B90A8EFD4225717A6A5C48CD3F99B2FC8Encoding) for key (根); 该类可以在源代码或未链接的库中定义' Blockquote *** First throw call stack: (0x18794d1b8 0x18638455c 0x1883f0408 0x1883f05c4 0x1883bc1cc 0x1883bbfa8 0x1883bb168 0x100085ff8 0x100076ec0 0x100076f6c 0x100219068 0x100075f2c 0x100078018 0x18d802924 0x18d8024ec 0x100074048 0x1000737dc 0x10007383c 0x1a34e2edc 0x1867d61fc 0x1867d61bc 0x1867dad68 0x1878fa810 0x1878f83fc 0x1878262b8 0x1892da198 0x18d86d7fc 0x18d868534 0x186a2bcc8 0x186a2d944 0x1885723c4 0x19001e128 0x19001dc90 0x19001e14c 0x1885580d4 0x1868095b8) libc++ abi.dylib:以 NSException 类型的未捕获异常终止

如何修复错误?

4

0 回答 0