从 iCloud 文件中取消归档对象时出错

Error when unarchiving objects from iCloud file

我有两个不同的应用程序(一个用 Objective-C 编写,一个用 Swift 编写)共享一些数据。我决定通过 iCloud 进行同步。要同步的项目打包在一个数组中,然后保存到一个文件中。同步 Objective-C 应用程序时,一切都按预期工作,但是当我尝试在 Swift 应用程序中下载文件时,出现以下错误:

Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason: '*** -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (Favourite) for key (NS.objects); the class may be defined in source code or a library that is not linked'

这里有两个 Favourite 类:

Objective C:

@interface Favourite : NSObject

@property(retain,nonatomic) NSString* mArtikeltext;
@property(retain,nonatomic) NSString* mRid;

-(instancetype) initWithObject:(NSMutableDictionary*) object;

@end

.m:

@implementation Favourite


-(instancetype) initWithObject:(NSMutableDictionary *)object{
    self = [super init];
    if(self){
        self.mArtikeltext = [object valueForKey:@"mArtikeltext"];
        self.mRid = [object valueForKey:@"mRid"];
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *) coder
{
    [coder encodeObject:self.mArtikeltext forKey:@"mArtikeltext"];
    [coder encodeObject:self.mRid forKey:@"mRid"];
}

- (id)initWithCoder:(NSCoder *)decoder {
    if (self = [super init]) {
        self.mArtikeltext = (NSString *)[decoder decodeObjectForKey:@"mArtikeltext"];
        self.mRid = (NSString *)[decoder decodeObjectForKey:@"mRid"];
    }


    return self;
}

@end

Swift:

class Favourite: NSObject, NSCoding {

    var mArtikeltext: String = ""
    var mRid: String = ""

    init(object: [String: AnyObject]) throws {
        super.init()
        guard case let (text as String, rid as String) = (object["mArtikelText"], object["mRid"]) else {
            throw JSONResponseError.NilResponseValue
        }
        self.mArtikeltext = text
        self.mRid = rid
    }

    required init?(coder aDecoder: NSCoder) {
        super.init()
        self.mArtikeltext = aDecoder.decodeObjectForKey("mArtikeltext") as! String
        self.mRid = aDecoder.decodeObjectForKey("mRid") as! String
    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(self.mArtikeltext, forKey: "mArtikeltext")
        aCoder.encodeObject(self.mRid, forKey: "mRid")
    }
}

这就是我在 Swift 中取消归档数据的方式:

let cloudFavs: [Favourite] = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! [Favourite]

并在 Objective-C 中:

NSArray *favs = [NSKeyedUnarchiver unarchiveObjectWithData:data];

关于如何修复错误的任何想法?

好的,经过更多的挖掘,我找到了答案。我必须在 swift class 中声明 Objective-C class 名称,如下所示:

@objc(Favourite)
class Favourite: NSObject, NSCoding {
    // and so on..

这解决了问题。