将结构数组保存/检索到iCloud

时间:2018-12-18 18:23:24

标签: arrays swift structure icloud

我实际上正在学习如何将数据保存到iCloud。我可以毫无问题地保存/检索字符串/数字,但是我有一个想要从云中保存/检索的struct变量,我不知道该怎么做。我尝试了许多不同的尝试,但没有结果。

也许有人可以给我一个可以从iCloud中保存/检索此变量“ Var2”的代码示例?

struct structure: Codable{
    var a : String!
    var b : String!
    var c : String!
    var d : String!
    var e : Double!
}

var Var2 = [
    structure(a: "-12.1", b: "5.9", c: "Hello", d: "2017-01-21 05:55:55", e: 5),
    structure(a: "151.17", b: "-1.8", c: "All", d: "2018-04-27 07:54:25", e: 0)
]

如果您需要我的实际代码:

import UIKit
import CloudKit

class ViewController: UIViewController {


    struct structure: Codable{
        var a : String!
        var b : String!
        var c : String!
        var d : String!
        var e : Double!}


    @IBAction func Button(_ sender: Any) {

        let Var1 = "Have Fun :)"     

        let Var2 = [
            structure(a: "-12.1", b: "5.9", c: "Hello", d: "2017-01-21 05:55:55", e: 5),
            structure(a: "151.17", b: "-1.8", c: "All", d: "2018-04-27 07:54:25", e: 0)]



        let MyRecord = CKRecord(recordType: "Test")

        // Changing the next line to "Var2" give an error
        MyRecord.setValue(Var1, forKey: "Content1")

        CKContainer.default().privateCloudDatabase.save(MyRecord) { (record, error) in
            guard record != nil else { return }
            print("saved record")
        }
    }
}

1 个答案:

答案 0 :(得分:0)

如注释中所部分提及,名称结构以大写字母开头,变量以小写字母开头,并声明成员为非可选

struct Structure: Codable {
    var a, b, c, d : String
    var e : Double
}

最有效的解决方案是创建一个具有与struct成员相对应的属性的新记录类型,并分别保存每个Structure实例

for item in var2 {    

   let myRecord = CKRecord(recordType: "Structure")
   myRecord["a"] = item.a as CKRecordValue
   myRecord["b"] = item.b as CKRecordValue
   // etc.
   myRecord["e"] = NSNumber(value: item.e)
}
...

或者将Content1属性声明为(NS)Data并用JSONEncoder编码结构数组

 do {
    let data = JSONEncoder().encode(var2)
    let myRecord = CKRecord(recordType: "Test")
    myRecord["Content1"] = data
 } catch { print(error) }