当前位置:网站首页>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 》
边栏推荐
- 剪掉ImageNet 20%数据量,模型性能不下降!Meta斯坦福等提出新方法,用知识蒸馏给数据集瘦身...
- 宝塔面板MySQL无法启动
- 把欧拉的创新带向世界 SUSE 要做那个引路人
- mysql80服务不启动
- Comment obtenir le temps STW du GC (collecteur d'ordures)?
- 【C语言】动态内存开辟的使用『malloc』
- ThreadLocal source code learning
- QT event filter simple case
- Unity粒子特效系列-毒液喷射预制体做好了,unitypackage包直接用 - 上
- 天龙八部TLBB系列 - 关于技能冷却和攻击范围数量的问题
猜你喜欢

TDengine ×英特尔边缘洞见软件包 加速传统行业的数字化转型

Cerebral Cortex:有向脑连接识别帕金森病中广泛存在的功能网络异常

QT event filter simple case

【C语言】动态内存开辟的使用『malloc』

盗版DALL·E成梗图之王?日产5万张图像,挤爆抱抱脸服务器,OpenAI勒令改名

美图炒币半年亏了3个亿,华为被曝在俄罗斯扩招,AlphaGo的同类又刷爆一种棋,今日更多大新闻在此...

Windows uses commands to run kotlin

How to choose the right chain management software?

卷起來,突破35歲焦慮,動畫演示CPU記錄函數調用過程

oracle 多行数据合并成一行数据
随机推荐
Getting started with Apache dolphin scheduler (one article is enough)
天龙八部TLBB系列 - 关于技能冷却和攻击范围数量的问题
Flutter development: use safearea
小程序启动性能优化实践
Charm of code language
观测云与 TDengine 达成深度合作,优化企业上云体验
把欧拉的创新带向世界 SUSE 要做那个引路人
卷起來,突破35歲焦慮,動畫演示CPU記錄函數調用過程
From "chemist" to developer, from Oracle to tdengine, two important choices in my life
Why don't you recommend using products like mongodb to replace time series databases?
La voie de l'évolution du système intelligent d'inspection et d'ordonnancement des petites procédures de Baidu
自动化规范检查软件如何发展而来?
Is it really reliable for AI to make complex decisions for enterprises? Participate in the live broadcast, Dr. Stanford to share his choice | qubit · viewpoint
移动端异构运算技术-GPU OpenCL编程(进阶篇)
idea用debug调试出现com.intellij.rt.debugger.agent.CaptureAgent,导致无法进行调试
Application of data modeling based on wide table
View Slide
Apache DolphinScheduler 系统架构设计
Roll up, break 35 - year - old Anxiety, animation Demonstration CPU recording Function call Process
Meitu lost 300 million yuan in currency speculation for half a year. Huawei was exposed to expand its enrollment in Russia. Alphago's peers have made another breakthrough in chess. Today, more big new