JSONDecoder().decode 从哪里获取数据?

Where does JSONDecoder().decode get it's data from?

如果这听起来很愚蠢,我很抱歉,但是 JSONDecoder 从哪里获取数据?我不断收到 "Grid" 和 "Red",所以我认为它只是解码我设置的这个虚拟对象,而不是上次程序 运行 中的 JSONEncoder().encode(myStarageObject)。这是我通过查看在线教程和示例管理的代码:

private func loadMyObject() -> MyObject? {
  let jsonString = """
  {
   "type":"Grid",
    "color":"Red",
    "lineThickness":2
  }
  """
  if let jsonData = jsonString.data(using: .utf8) {
    do {
      let loadedObject = try JSONDecoder().decode(myStorageStruct.self,from: jsonData)
      print("I loaded type \(loadedObject.type) of color: \(loadedObject.color)")
      return makeMyObjectFromStorageData(loadedObject)
      } else {
        return nil
      }
    } catch  let error { print(error) }
  } else {
    return nil
  }
return nil
}

如果您希望写入文件并稍后从中读取,则需要手动执行这些操作。

要写:

let json: Data
do {
    // encoder is a JSONEncoder
    json = try encoder.encode(someObject)
} catch {
    // Failure to encode. Do something sensible with `error`.
}

do {
    try json.write(to: archiveURL)
} catch {
    // Failure to write to disk. Do something sensible with `error`.
}

阅读:

let json: Data
do {
    json = try Data(contentsOf: archiveURL)
} catch {
    // Failure to read from disk. Do something sensible with `error`.
}

// Replace MyType with the actual type.
let someObject: MyType
do {
    // decoder is a JSONDecoder
    someObject = try decoder.decode(MyType.self, from: json)
} catch {
    // Failure to decode. Do something sensible with `error`.
}

您可以根据您计划如何处理错误来缩短这些示例,但这是要点。

对于少量的数据存储,我发现用

let userDefaults = UserDefaults.standard
userDefaults.set(yourTypeVariable,"type")

和阅读

let userDefaults = UserDefaults.standard
let defaultType = userDefaults.string("type")

工作得很好。