惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Y
Y Combinator Blog
V
V2EX
Jina AI
Jina AI
爱范儿
爱范儿
M
MIT News - Artificial intelligence
量子位
L
LangChain Blog
Google DeepMind News
Google DeepMind News
酷 壳 – CoolShell
酷 壳 – CoolShell
罗磊的独立博客
腾讯CDC
MongoDB | Blog
MongoDB | Blog
P
Proofpoint News Feed
宝玉的分享
宝玉的分享
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Last Week in AI
Last Week in AI
H
Hackread – Cybersecurity News, Data Breaches, AI and More
F
Fortinet All Blogs
The GitHub Blog
The GitHub Blog
Engineering at Meta
Engineering at Meta
博客园 - 聂微东
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Vercel News
Vercel News
T
The Blog of Author Tim Ferriss

木土金王可

复盘 2024,年度好物分享 落地 第二十台相机:宝丽来(Polaroid)Impulse AF 第十九台相机:哈苏(Hasselblad)X1D II 第十八台相机:宝丽来(Polaroid)Macro 5 SLR 第十七台相机:康泰时(Contax)S2 稻荷山 Dave Chappelle: The Closer 语言是思想的边界 对街头卖惨表演的看法 《民主森林》 电梯英雄 2023,年度好物分享 《大画幅 4x5》复活 新加坡华侨银行(OCBC)开户指南 第十六台相机:宾得(Pentax)PC35AF-M SEDATE 第十五台相机:沙慕尼(Chamonix)4x5 F2 Xbox 连接 Studio Display Twitter、Apple、Meta 和 Reddit 广告平台使用体验 第十四台相机:康泰时(Contax)S2 你到底什么时候买相机 拍摄胶片的理由 HomePod 不能作为 Mac 音响 男性生来就是残缺的女性 第十三台相机:柯尼卡(Konica)Big Mini 301 三年,十二台相机 恐怖片很好看啊 比残忍更残忍 用 SwiftUI 重构「行动日」
以配置信息(UserDefaults)的形式存储应用数据
kinnouka bokudo · 2018-09-10 · via 木土金王可

存储配置信息,可以使用 UserDefaults,这是一种最简单的储存数据的方法,适合用来储存轻量级的数据,UserDefaults 支持储存的数据类型只有 DataStringNumberDateArrayDictionary 这几种。

声明:笔者自身对 UserDefaults 也是初学,而本文介绍的 UserDefaults 知识也都是自己的一些理解,同时尽量不涉及过于原理性的内容,一切以普通工程师实用为目标原则。其中可以想象在很多地方会有理解的错误,还请多包涵。如您发现问题,也往不吝赐教指正,感激不尽。

储存

储存值为「Hello」的字符串:

UserDefaults.standard.set("Hello", forKey: "helloString")

而如果准备将储存的数据在主程序(Container)和其他扩展(Extensions)之间传递,则需要在 UserDefaults 中添加 Group 字符串:

UserDefaults.init(suiteName: "group.com.xxx.xxx")?.set("hello", forKey: "helloString")

加载

加载 Key 值为「helloString」的数据:

let helloStr = UserDefaulte.standard.object(forKey: "helloString")

print(helloStr)
// Output: Hello

同样在其他扩展(Extensions)中,也需要添加 Group 字符串,才能加载相应数据。

let helloString = UserDefaults.init(suiteName: "group.com.xxx.xxx")?.value(forKey: "helloString")

print(helloStr)
// Output: Hello

2018 年 9 月 10 日