UITableView显示JSON或Object,哪个更好

时间:2019-03-12 08:51:01

标签: ios swift uitableview

通常,我们请求获取一些JSON数据,然后将其显示在UITableView中,我们真的需要将JSON转换为对象然后显示吗?

例如,从服务器检索的数据:

[
   { 
     key1: value1,
     key2: value1,
     key2: value3
   },
   { 
     key1: value1,
     key2: value1,
     key2: value3
   },
   ...
   { 
     key1: value1,
     key2: value1,
     key2: value3
   }
]

选项1 直接显示

我们将这些数据保存到一个数组中

var jsonArray = [[String: Any?]]()

在tableView单元格中:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  let jsonElement = jsonArray[indexPath.row]
  cell.configure(jsonElement)
}

选项2 :将其转换为要显示的结构/对象。

定义对象/结构:

   struct JsonObject {
       var key1: String
       var key2: Date
       var key3: Int
    }

转换:

let jsonObjects: [JsonObject] = jsonArray.map { jsonElement in
   JsonObject(convert(jsonElement))
}

显示

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      let jsonObject = jsonObjects[indexPath.row]
      cell.configure(jsonObject)
    }

那么哪个选项更好?转换是否存在我们应关注的性能问题? 谢谢!

0 个答案:

没有答案
相关问题