上一篇文章我 hard code 了一些数据进去我的专案,
现在要来把这些数据放进 JSON 文件里,
并将这些接入 app。
let pathString = Bundle.main.path(forResource: "recipes", ofType: "json")
guard pathString != nil else {
return [Recipe]()
}
创建 url 对象:
let url = URL(fileURLWithPath: pathString!)
创建数据对象:
do {
let data = try Data(contentsOf: url)
}
catch {
print(error)
}
解码:
let decoder = JSONDecoder()
do {
let recipeData = try decoder.decode([Recipe].self, from: data)
}
catch {
print(error)
}
设置 id:
for r in recipeData {
r.id = UUID()
}
return recipeData
会看到 Xcode 显示一个 error,
因为我们可能创建数据失败,
所以需要回传一个空的 Recipe array:
4. 回到 ViewModel 在 init 创建实例获取数据:
因为我们会反复调用 class DataServise 里的 function,
所以用 static 修饰这个 function,
使其变成一种静态方法,不需创建实例就能直接调用。
<<: 【Day 23】Go 基础小笔记 IV:goroutine、channel
>>: [Day 23] SQL left / right join
前几篇讲这麽多, 来介绍一个服务Fleunt Bit Fleunt Bit 它是一个开源的数据收集器...
上回说到歌伦比亚大学制作的类似AR眼镜的装置,今天!还是歌伦比亚大学 1996-1997年 他们在1...
读写档案 | 跳脱字元\ | 逐字识别码@ | DateTime | Random ...
最後几天来回顾一下在过去开发资料产品时常见的坑与应对方式,不管是专案还是产品,首先当然要面对的难题就...
在切回去写 domain layer 之前,我们先把之前写好的 data layer class 补...