如何在Swift应用中保存本地数据?


在Swift中,有多种方法可以保存应用程序中的本地数据,具体取决于要保存的数据类型和大小。可以使用UserDefaults、属性列表序列化、Core Data等。本文将介绍UserDefaults并提供一些示例。

UserDefaults

在iOS、macOS和watchOS中,一个称为UserDefaults的基本存储机制允许应用程序存储相对少量的数据,包括用户偏好设置或设置。它使用键值对系统,将值赋给特定的键,然后使用该键来检索值。

UserDefaults通常存储简单的数据类型,例如文本、布尔值、整数和日期。它易于使用,不需要其他框架或库。

以下是UserDefaults的一些主要特性:

  • 数据持久性 − 即使应用程序关闭或设备重启,UserDefaults数据仍然可用。

  • 简单的API − 通过键轻松设置和获取值,易于使用。

  • 快速 − UserDefaults专为快速读取和写入而设计,对于少量数据来说是一个不错的选择。

  • 安全 − UserDefaults数据安全地保存在应用程序的沙盒中,这意味着只有创建它的应用程序才能访问它。

以下是一些在Swift中使用UserDefaults的更多示例:

示例1:保存和检索布尔值

import Foundation
// Set a boolean value for the key "isDarkModeEnabled"
let defaults = UserDefaults.standard
defaults.set(true, forKey: "isDarkModeEnabled")

// Retrieve the boolean value for the key "isDarkModeEnabled"
let isDarkModeEnabled = defaults.bool(forKey: "isDarkModeEnabled")
print(isDarkModeEnabled)

输出

true

此示例演示如何使用set方法和键“isDarkModeEnabled”将布尔值保存到UserDefaults。然后,它使用bool方法和相同的键检索布尔值。最后,它打印出检索到的布尔值。

示例2:保存和检索字符串数组

import Foundation
// Set an array of strings for the key "myArray"
let defaults = UserDefaults.standard
defaults.set(["Apple", "Banana", "Orange"], forKey: "myArray")

// Retrieve the array of strings for the key "myArray"
let myArray = defaults.array(forKey: "myArray") as? [String] ?? []
print(myArray)

输出

["Apple", "Banana", "Orange"]

此示例演示如何使用set方法和键“myArray”将字符串数组保存到UserDefaults。然后,它使用array方法和相同的键检索数组,并将其转换为字符串数组。如果由于某种原因转换失败,它将默认为空数组。最后,它打印出检索到的数组。

示例3:保存和检索整数

import Foundation
// Set an integer value for the key "myInt"
let defaults = UserDefaults.standard
defaults.set(42, forKey: "myInt")

// Retrieve the integer value for the key "myInt"
let myInt = defaults.integer(forKey: "myInt")
print(myInt)

输出

42

此示例演示如何使用set方法和键“myInt”将整数值保存到UserDefaults。然后,它使用integer方法和相同的键检索整数值。最后,它打印出检索到的整数值。

示例4:保存和检索字典

import Foundation
// Set a dictionary for the key "myDictionary"
let defaults = UserDefaults.standard
defaults.set(["name": "John", "age": 30], forKey: "myDictionary")

// Retrieve the dictionary for the key "myDictionary"
let myDictionary = defaults.dictionary(forKey: "myDictionary") as? [String: Any] ?? [:]
print(myDictionary)

输出

["name": John, "age": 30]

此示例演示如何使用set方法和键“myDictionary”将字典保存到UserDefaults。然后,它使用dictionary方法和相同的键检索字典,并将其转换为键为String,值为Any的字典。如果由于某种原因转换失败,它将默认为空字典。最后,它打印出检索到的字典。

结论

总而言之,UserDefaults是iOS、macOS和watchOS中的基本存储机制。它允许应用程序存储少量信息,例如用户偏好设置或设置。它使用键值对系统,将值赋给特定的键,然后使用该键来检索值。

UserDefaults非常适合存储基本数据类型,因为它易于使用,不需要其他库或框架。但是,它并非旨在处理大型数据集或更复杂的数据类型,因此在某些情况下,您可能需要使用Core Data、SQLite数据库或属性列表作为替代存储方法。

更新于:2023年5月4日

3K+ 次浏览

启动您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.