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

时间:2018-01-29 20:03:04

标签: ios swift jsondecoder

我很抱歉,如果这听起来很愚蠢,但JSONDecoder从哪里获取数据?我一直得到“网格”和“红色”所以我认为它只是解码我设置的虚拟,而不是上次程序运行时的JSONEncoder()。编码(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
}

2 个答案:

答案 0 :(得分:0)

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

写:

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`.
}

您可以根据计划处理错误的方式缩短这些示例,但这是要点。

答案 1 :(得分:0)

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

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

并阅读

SELECT P.*                      
FROM MyTable AS P
WHERE CONTAINS(P.*, 'FORMSOF(INFLECTIONAL, "Carlo")')

工作得很好。