当前位置:网站首页>Swift uses userdefaults and codable to save an array of class objects or structure instances
Swift uses userdefaults and codable to save an array of class objects or structure instances
2022-07-05 10:10:00 【cppphp】
swift use UserDefaults And Codable Save an array of class objects or structure instances
I wrote an article before 《swift use UserDefaults And NSSecureCoding Save an array of class objects 》 The article , Although it can save class and structure arrays , But in actual use, each class or structure to be saved should be encoded and decoded , There is also more code when saving and reading , It is complicated to use , Especially when saving and reading arrays are frequent .
This article uses swift4.0 Agreement brought by Codable To solve the problems mentioned above .
Codable It is based on the basic agreement Encodable,Decodable,CodingKey Above . The specific content will not be expanded . In this article, its use is very simple , Just inherit the protocol when defining classes and structures . The code is as follows :
struct Item: Codable {
var uuid: UUID
var inAction: Int
var outAction: Int
var useful: Bool
}
Just follow the above definition , Don't ask 《swift use UserDefaults And NSSecureCoding Save an array of class objects 》 Then write the coding and decoding code as in , Is it simple .
To further simplify the code , Easy to use , Yes UserDefaults Expand as follows
extension UserDefaults {
// Save the class array
func set<T:Encodable>(classArrory object: [T], key: String) {
do {
let data = try JSONEncoder().encode(object)
self.set(data, forKey: key)
} catch {
print(error)
}
}
// Read the class array
func classArrory<T:Decodable>(forKey key : String) -> [T] {
guard let data = self.data(forKey: key) else { return [] }
do {
return try JSONDecoder().decode([T].self, from: data)
} catch {
print(error)
}
return []
}
}
In the above code , function set The main function is to encode and save the structure array , function classArrory Its main function is to read structural data and decode , Template parameters are used in both functions T, To specify different classes and structures . There is nothing else to say , Very simple, at a glance .
The foundation has been laid , Let's see how to use it
let ud = UserDefaults.standard
let item1 = Item(uuid: "00000023-0000-1000-8000-0026BB765291", inAction: 0, outAction: 1, useful: true)
let item2 = Item(uuid: "0000003E-0000-1000-8000-0026BB765475", inAction: 1, outAction: 1, useful: true)
var items = [item1, item2]
// Save the class array
ud.set(classArrory: items, key: "homekits")
...
// Read the class array
items = ud.classArrory(forKey: "homekits")
After defining the array , Write... In one line , One line readout , Is it simple ?
Related blogs
《swift use UserDefaults And NSSecureCoding Save an array of class objects 》
边栏推荐
- Uncover the practice of Baidu intelligent testing in the field of automatic test execution
- 90%的人都不懂的泛型,泛型的缺陷和应用场景
- 【小技巧】获取matlab中cdfplot函数的x轴,y轴的数值
- B站大量虚拟主播被集体强制退款:收入蒸发,还倒欠B站;乔布斯被追授美国总统自由勋章;Grafana 9 发布|极客头条...
- 程序员如何活成自己喜欢的模样?
- 自动化规范检查软件如何发展而来?
- Coordinate system of view
- (1) Complete the new construction of station in Niagara vykon N4 supervisor 4.8 software
- [200 opencv routines] 219 Add digital watermark (blind watermark)
- 如何获取GC(垃圾回收器)的STW(暂停)时间?
猜你喜欢
TDengine 连接器上线 Google Data Studio 应用商店
On July 2, I invite you to TD Hero online press conference
Evolution of Baidu intelligent applet patrol scheduling scheme
Baidu app's continuous integration practice based on pipeline as code
一种用于干式脑电图的高密度256通道电极帽
Coordinate system of view
How to implement complex SQL such as distributed database sub query and join?
观测云与 TDengine 达成深度合作,优化企业上云体验
Mobile heterogeneous computing technology GPU OpenCL programming (Advanced)
Apache DolphinScheduler 入门(一篇就够了)
随机推荐
Fluent development: setting method of left and right alignment of child controls in row
能源势动:电力行业的碳中和该如何实现?
Observation cloud and tdengine have reached in-depth cooperation to optimize the cloud experience of enterprises
Getting started with Apache dolphin scheduler (one article is enough)
Tdengine can read and write through dataX, a data synchronization tool
Charm of code language
解决Navicat激活、注册时候出现No All Pattern Found的问题
Resolve the horizontal (vertical) sliding conflict between viewpager and WebView
程序员搞开源,读什么书最合适?
Cerebral Cortex:有向脑连接识别帕金森病中广泛存在的功能网络异常
cent7安装Oracle数据库报错
【技术直播】如何用 VSCode 从 0 到 1 改写 TDengine 代码
Kotlin compose and native nesting
Unity粒子特效系列-毒液喷射预制体做好了,unitypackage包直接用 -下
基于单片机步进电机控制器设计(正转反转指示灯挡位)
TDengine 连接器上线 Google Data Studio 应用商店
卷起来,突破35岁焦虑,动画演示CPU记录函数调用过程
正式上架!TDengine 插件入驻 Grafana 官网
TDengine可通过数据同步工具 DataX读写
Oracle combines multiple rows of data into one row of data