当前位置:网站首页>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 》
边栏推荐
- Resolve the horizontal (vertical) sliding conflict between viewpager and WebView
- 从“化学家”到开发者,从甲骨文到 TDengine,我人生的两次重要抉择
- Solve liquibase – waiting for changelog lock Cause database deadlock
- 让AI替企业做复杂决策真的靠谱吗?参与直播,斯坦福博士来分享他的选择|量子位·视点...
- 【小技巧】獲取matlab中cdfplot函數的x軸,y軸的數值
- The essence of persuasion is to remove obstacles
- 如何正确的评测视频画质
- Baidu app's continuous integration practice based on pipeline as code
- How to use sqlcipher tool to decrypt encrypted database under Windows system
- Are databases more popular as they get older?
猜你喜欢

Tongweb set gzip

如何获取GC(垃圾回收器)的STW(暂停)时间?

Develop and implement movie recommendation applet based on wechat cloud
![[NTIRE 2022]Residual Local Feature Network for Efficient Super-Resolution](/img/f3/782246100bca3517d95869be80d9c5.png)
[NTIRE 2022]Residual Local Feature Network for Efficient Super-Resolution

Wechat applet - simple diet recommendation (3)

写入速度提升数十倍,TDengine 在拓斯达智能工厂解决方案上的应用

How to implement complex SQL such as distributed database sub query and join?

Cent7 Oracle database installation error

Observation cloud and tdengine have reached in-depth cooperation to optimize the cloud experience of enterprises

Uncover the practice of Baidu intelligent testing in the field of automatic test execution
随机推荐
B站大量虚拟主播被集体强制退款:收入蒸发,还倒欠B站;乔布斯被追授美国总统自由勋章;Grafana 9 发布|极客头条...
Solve the problem of no all pattern found during Navicat activation and registration
Tdengine connector goes online Google Data Studio app store
Are databases more popular as they get older?
【 conseils 】 obtenir les valeurs des axes X et y de la fonction cdfplot dans MATLAB
tongweb设置gzip
Roll up, break 35 - year - old Anxiety, animation Demonstration CPU recording Function call Process
程序员搞开源,读什么书最合适?
The king of pirated Dall · e? 50000 images per day, crowded hugging face server, and openai ordered to change its name
Cerebral Cortex:有向脑连接识别帕金森病中广泛存在的功能网络异常
Online chain offline integrated chain store e-commerce solution
Tianlong Babu TLBB series - single skill group injury
[tips] get the x-axis and y-axis values of cdfplot function in MATLAB
Idea debugs com intellij. rt.debugger. agent. Captureagent, which makes debugging impossible
单片机原理与接口技术(ESP8266/ESP32)机器人类草稿
Kotlin Compose 多个条目滚动
How to use sqlcipher tool to decrypt encrypted database under Windows system
[NTIRE 2022]Residual Local Feature Network for Efficient Super-Resolution
TDengine 离线升级流程
硬核,你见过机器人玩“密室逃脱”吗?(附代码)