首页 > 解决方案 > 我在一个类的静态变量中拥有所有重要的东西,但我似乎找不到保存它的方法。有什么建议么?斯威夫特 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: [])]
}

标签: swiftclassstatic

解决方案


您可以使您的对象符合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")

推荐阅读