4

Swift 中的 SharedPreferance —— UserDefaults

 3 years ago
source link: https://aeilot.github.io/2020/08/24/swift-userdefaults/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Swift 中的 SharedPreferance —— UserDefaults

发表于

2020-08-24 更新于 2021-01-25 分类于 编程

阅读次数: 9 Valine:
本文字数: 835 阅读时长 ≈ 1 分钟

从 Android 开发又最终回到 iOS 了,好多东西都不知道。最近一直有需求要用一个类似 Android 的 SharedPreferance 的东西。找了一下资料,来总结一下。

不会吧?不会还有人不知道 SharedPreferance 吧???

SharedPreferance 是一种轻量级的 Android 储存 API, 用于储存简单的数据,数据多了就不如其他方式高效了。

iOS 中,起同样作用的东西,叫 UserDefaults

这两者都以 key-value 的形式存储。

简单数据

简单数据

简单数据

复杂数据建议使用 SQLite 或者 Core Data,不建议作死。。。

Quick Start

直接上代码,里面注释我都写好了。

let defaults = UserDefaults.standard // 获取全局的 UserDefaults

defaults.set(Int.max, forKey: "int") // 存储
defaults.integer(forKey: "int") // 读取

defaults.set(true, forKey: "bool")
defaults.bool(forKey: "bool")

defaults.set(Double.infinity, forKey: "double")
defaults.double(forKey: "double")

defaults.set(Float.infinity, forKey: "float")
defaults.float(forKey: "float")

Float, Int, Double 的默认值都是 0;Bool 的默认值是 false。

大家可以多在 Playgrounds 里面试试,还可以看看 Apple Developer Documentation


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK