当前位置:网站首页>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 》
边栏推荐
- How to choose the right chain management software?
- Theme. AppCompat. Light. Darkactionbar not found
- Openes version query
- Roll up, break through 35 year old anxiety, and animate the CPU to record the function call process
- 【C语言】动态内存开辟的使用『malloc』
- How to use sqlcipher tool to decrypt encrypted database under Windows system
- Six simple cases of QT
- Unity particle special effects series - the poison spray preform is ready, and the unitypackage package is directly used - on
- About getfragmentmanager () and getchildfragmentmanager ()
- Charm of code language
猜你喜欢
盗版DALL·E成梗图之王?日产5万张图像,挤爆抱抱脸服务器,OpenAI勒令改名
Node-RED系列(二九):使用slider与chart节点来实现双折线时间序列图
【OpenCV 例程200篇】219. 添加数字水印(盲水印)
写入速度提升数十倍,TDengine 在拓斯达智能工厂解决方案上的应用
苹果 5G 芯片研发失败?想要摆脱高通为时过早
[200 opencv routines] 219 Add digital watermark (blind watermark)
Common fault analysis and Countermeasures of using MySQL in go language
Six simple cases of QT
为什么不建议你用 MongoDB 这类产品替代时序数据库?
程序员如何活成自己喜欢的模样?
随机推荐
卷起來,突破35歲焦慮,動畫演示CPU記錄函數調用過程
Tianlong Babu TLBB series - about items dropped from packages
Evolution of Baidu intelligent applet patrol scheduling scheme
高级 OpenCV:BGR 像素强度图
The comparison of every() and some() in JS uses a power storage plan
正式上架!TDengine 插件入驻 Grafana 官网
Observation cloud and tdengine have reached in-depth cooperation to optimize the cloud experience of enterprises
Implementation of smart home project
Apache DolphinScheduler 系统架构设计
Six simple cases of QT
About getfragmentmanager () and getchildfragmentmanager ()
Getting started with Apache dolphin scheduler (one article is enough)
如何正确的评测视频画质
Cut off 20% of Imagenet data volume, and the performance of the model will not decline! Meta Stanford et al. Proposed a new method, using knowledge distillation to slim down the data set
Why don't you recommend using products like mongodb to replace time series databases?
MySQL character type learning notes
La voie de l'évolution du système intelligent d'inspection et d'ordonnancement des petites procédures de Baidu
[200 opencv routines] 219 Add digital watermark (blind watermark)
Those who are good at using soldiers, hide in the invisible, and explain the best promotional value works in depth in 90 minutes
Kotlin compose multiple item scrolling