swift - 我在一个类的静态变量中拥有所有重要的东西,但我似乎找不到保存它的方法。有什么建议么?斯威夫特 4
问题描述
我是 Swift 的初学者,但我已经完成了 Apple 的应用程序开发课程,并且我开始了一个名为 Training Hub 的大项目,其中有很多很多事情在应用程序关闭后我必须记住。
我在一个类中拥有所有信息,保存为静态变量,但我不知道如何将它们保存到磁盘以便能够加载和保存它们。
在应用程序中,用户能够更改主题、添加例程、锻炼、练习、日志集,以日历格式查看旧会话,因此他能够自定义内容,我必须记住他所做的更改。
class User {
static var name: String = "Alex"
static var weight = Weight(kg: 0)
static var height = Height(metres: 0, centimetres: 0)
static var bodyFat = BodyFat()
static var bodyType: String = "Male"
static var goals: [Goal] = []
static var routines: [Routine] = [
Routine(name: "TestRoutine1", workouts: [], type: routineType[0], creator: "Training Hub", rating: rating[3], notes: nil),
Routine(name: "TestRoutine2", workouts: [], type: routineType[0], creator: "Training Hub", rating: rating[3], notes: nil)]
static var currentUnit: String = "Metric"
static var sessions: Dictionary<String, Session> = [:]
static var measurements: [Measurement] = [
Measurement(bodyPart: "Wrist", point: "at fullest point", circumference: Circumference(inches: 0), entry: []),
Measurement(bodyPart: "Waist", point: "at navel", circumference: Circumference(inches: 0), entry: []),
Measurement(bodyPart: "Hip", point: "at fullest point", circumference: Circumference(inches: 0), entry: []),
Measurement(bodyPart: "Forearm", point: "at fullest point", circumference: Circumference(inches: 0), entry: []),
Measurement(bodyPart: "Chest", point: "at middle of sternum", circumference: Circumference(inches: 0), entry: []),
Measurement(bodyPart: "Shoulders", point: "at fullest point", circumference: Circumference(inches: 0), entry: []),
Measurement(bodyPart: "Biceps", point: "at fullest point", circumference: Circumference(inches: 0), entry: []),
Measurement(bodyPart: "Quadriceps", point: "at fullest point", circumference: Circumference(inches: 0), entry: []),
Measurement(bodyPart: "Calf", point: "at fullest point", circumference: Circumference(inches: 0), entry: []),
Measurement(bodyPart: "Neck", point: "at fullest point", circumference: Circumference(inches: 0), entry: [])]
}
解决方案
您可以使您的对象符合Codable
协议(例如):
class User: Codable {
//all the stuff goes here
}
然后使用这个简单的功能将它们保存在您的文档目录中
static func store<T: Encodable>(_ object: T, as fileName: String) {
guard let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
fatalError("Could not create URL!")
}
let completeUrl = url.appendingPathComponent(fileName, isDirectory: false)
let encoder = JSONEncoder()
do {
let data = try encoder.encode(object)
if FileManager.default.fileExists(atPath: completeUrl.path) {
try FileManager.default.removeItem(at: completeUrl)
}
FileManager.default.createFile(atPath: completeUrl.path, contents: data, attributes: nil)
} catch {
fatalError(error.localizedDescription)
}
}
用法:
store(user, as: "current_user.json")
推荐阅读
- c - 尝试使用结构变量时遇到问题
- react-native - 在 React Native 中具有相同标识符的 JSON 数组
- shell - 如何在shell中使用@将复杂的表达式分配给变量
- php - 将 JSON 对象从 Xamarin 获取到 PHP?
- javascript - 使用 fs nodejs 搜索文件内的内容
- java - 为什么不在实现 BeanFactoryPostProcessor 和 ApplicationContextAware 的 bean 上调用 @PostConstruct?
- php - 在laravel中访问数组索引时数组打印好但未定义的索引
- angular - 使用 rxjs retryWhen 零重试时如何抛出原始错误
- php - preg_match_all 前后添加字符
- python - 建模时如何使用 R^2 作为评估指标?