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

推荐订阅源

J
Java Code Geeks
IT之家
IT之家
爱范儿
爱范儿
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园_首页
Blog — PlanetScale
Blog — PlanetScale
V
Visual Studio Blog
云风的 BLOG
云风的 BLOG
MyScale Blog
MyScale Blog
阮一峰的网络日志
阮一峰的网络日志
Stack Overflow Blog
Stack Overflow Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
GbyAI
GbyAI
V
V2EX
N
Netflix TechBlog - Medium
Vercel News
Vercel News
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
The Blog of Author Tim Ferriss
量子位
博客园 - Franky
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 司徒正美
月光博客
月光博客
F
Fortinet All Blogs

Louis C Deng's Blog

RoPE: Properties, Patterns, and Long-Context Behavior CS336 Assignment 1: Large Language Model Training and Inference CS231n Lecture Note: Generative Models CS231n Lecture Note: Self-Supervised Learning CS231n Lecture Note: Large Scale Distributed Training 自動微分 | DIY 實現自己的 PyTorch From RNNs to Transformers CS231n Lecture Note VII: Recurrent Neural Networks Uncovering Batch & Layer Normalization CS231n Lecture Note VI: CNN Architectures and Training CS231n Lecture Note V: Convolution Neural Networks Basics Demystifying Softmax Loss: A Step-by-Step Derivation for Linear Classifiers Backpropagation: A Vector Calculus Perspective CS231n Lecture Note IV: Neural Networks and Backpropagation CS231n Lecture Note III: Optimization CS231n Lecture Note II: Linear Classifiers CS231n Lecture Note I: Image Classification CSAPP Cache Lab II: Optimizing Matrix Transposition CSAPP Cache Lab I: Let's simulate a cache memory! CS188 Search Lecture Notes III CS188 Search Lecture Notes II How to Use TouchID for Sudo Commands on macOS CS188 Search Lecture Notes I RECAP2025: 留白 CSAPP Bomb Lab 解析 x64 暫存器速查表 CSAPP Data Lab 解析 矩陣的 Modified Gram Schmidt 方法 聊一聊位掩碼(Bit Mask) 整數溢位與未定義行為
Swift 中的 SharedPreferance —— UserDefaults
Louis C Deng · 2020-08-24 · via Louis C Deng's Blog

從 Android 開發又最終回到 iOS 了,好多東西都不知道。最近一直有需求要用一個類似 Android 的 SharedPreferance 的東西。找了一下資料,來總結一下。

它是什麼

不會吧?不會還有人不知道 SharedPreferance 吧???

SharedPreferance 是一種輕量級的 Android 儲存API, 用於儲存簡單的資料,資料多了就不如其他方式高效了。

iOS 中,起同樣作用的東西,叫 UserDefaults

這兩者都以 key-value 的形式儲存。

使用場景

簡單資料

簡單資料

簡單資料

複雜資料建議使用 SQLite 或者 Core Data,不建議作死。。。

Quick Start

直接上程式碼,裡面註釋我都寫好了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
let defaults = UserDefaults.standard 

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