从iCloud文件

时间:2015-11-30 12:52:57

标签: ios objective-c swift icloud

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

  

由于未捕获的异常'NSInvalidUnarchiveOperationException'终止应用程序,原因:'*** - [NSKeyedUnarchiver decodeObjectForKey:]:无法解码类(收藏夹)对象的密钥(NS.objects);该类可以在源代码中定义,也可以在未链接的库中定义

以下是Favourite个类:

目标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
斯威夫特:

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];

如何修复错误?

1 个答案:

答案 0 :(得分:0)

好的,经过一番挖掘后,我找到了答案。我必须在swift类中声明Objective-C类名,如下所示:

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

这解决了这个问题。