使用Locksmith Swift 3更新数据部分

时间:2016-11-05 07:52:13

标签: swift swift3

假设我最初使用Locksmith存储了一些数据:

                    do
                    {

                        try Locksmith.saveData(data: ["a": a_data, "b":b_data, "c":c_data, "d":d_data], forUserAccount: "user") //store it
                        print("Data successfully Saved.")
                    } catch ...

是否可以稍后返回并仅更新特定字段而不覆盖存储在钥匙串中的现有数据。例如,如果我最初存储了a,b,c和d。当我用:

更新字段b时
try Locksmith.updateData(["b": "new"], forUserAccount: "user")

我是否只用新数据(即a,b,c,d - > new_b)覆盖a,b,c,d,或者Locksmiths更新功能是否只更新特定字段。我应该提一下,我试图在文档中找到答案,但似乎无法找到答案,除非我忽略了它。在那种情况下,我道歉。不过,任何帮助都表示赞赏。

由于

1 个答案:

答案 0 :(得分:1)

我相信文档很清楚,可用的静态Locksmith.updateData(_:, forUserAccount:)方法替换用户的任何给定数据。我引用matthewpalmer/Locksmith [强调我的]

  

更新数据

     

以及替换现有数据,这会将数据写入   钥匙串,如果它已经不存在

try Locksmith.updateData(["some key": "another value"], 
                         forUserAccount: "myUserAccount")

我们可以通过查看以下非失败测试(Locksmith/Tests/LocksmithTests.swift)来验证此声明:

// ....

let userAccount = "myUser"

func testStaticMethods() {
    // ...    

    let otherData: TestingDictionaryType = ["something": "way different"]

    // ...

    let updatedData = ["this update": "brings the ruckus"]
    try! Locksmith.updateData(data: updatedData, forUserAccount: userAccount, inService: service)

    let loaded3 = Locksmith.loadDataForUserAccount(userAccount: userAccount, inService: service)! as! TestingDictionaryType

    // NOTE: this assert checks that the loaded data equals the 
    //       updated data (_not_ 'otherData' updated by 'updatedData')
    XCTAssertEqual(loaded3, updatedData)

    // ...
}

静态Locksmith.updateData(_:, forUserAccount:)方法明确替换给定用户帐户的数据。

如果您只想将子数据添加到用户的现有数据中,您可以自己实现:

  1. 读取给定用户帐户的数据

    let currentData = Locksmith.loadDataForUserAccount(userAccount: userAccount)
    
  2. 手动更新数据字典。存在许多解释该步骤的SO线程,参见例如

  3. 使用Locksmith.saveData(_:, forUserAccount:)静态方法保存给定用户帐户的更新数据。