在NSData中转换CKRecord

时间:2016-03-02 02:56:28

标签: swift nsdata ckrecord

我正在尝试在我的NSUserDefaults上存储CKRecord。但据我所知,默认值不会占用CKRecords,但会采用NSData。

我正在寻找有关如何将CKRecord转换为NSData的帮助。是否有可能完成?

至NSData

func set_activeLinkRequest(record: CKRecord) {
        print("PublicUsers - set_activeLinkRequest \(record)")

        var data = NSData()

        // convert the record into NSData

        NSUserDefaults.standardUserDefaults().setObject(data, forKey: "activeLinkRequest")
        NSUserDefaults.standardUserDefaults().synchronize()
    }

返回CKRecord

func get_activeLinkRequest() -> CKRecord {
    let record = NSUserDefaults.standardUserDefaults().objectForKey("activeLinkRequest") as! NSData

    // convert NSDate into CKRecord

    print("PublicUsers = get_activeLinkRequest \(value)")
    return record
}

2 个答案:

答案 0 :(得分:2)

这是解决方案,希望它可以帮助他人。

CKRecord到NSData到NSUserDefaults

func set_activeLinkRequest(record: CKRecord) {
    print("PublicUsers - set_activeLinkRequest \(record)")

    let data = NSKeyedArchiver.archivedDataWithRootObject(record)

    NSUserDefaults.standardUserDefaults().setObject(data, forKey: "activeLinkRequest")
    NSUserDefaults.standardUserDefaults().synchronize()
}

NSUserDefaults到NSData到CKRecord

func get_activeLinkRequest() -> CKRecord {

     let data = NSUserDefaults.standardUserDefaults().objectForKey("activeLinkRequest") as! NSData      
     let record = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! CKRecord

     print("PublicUsers = get_activeLinkRequest \(record)")
     return record
}

答案 1 :(得分:0)

快捷键5

func setActiveLinkRequest(record: CKRecord) {
    do {
        let data = try NSKeyedArchiver.archivedData(withRootObject: record, requiringSecureCoding: false)

        UserDefaults.standard.set(data, forKey: "activeLinkRequest")
    } catch {
        print(error)
    }
}

func getActiveLinkRequest() -> CKRecord? {

    guard let data = UserDefaults.standard.object(forKey: "activeLinkRequest") as? Data else {
        return nil
    }
    do {
        let record = try NSKeyedUnarchiver.unarchivedObject(ofClass: CKRecord.self, from: data)
        return record
    } catch {
        print(error)
        return nil
    }
}