У меня есть все важные вещи в статических переменных внутри класса, и я не могу найти способ сохранить его. Какие-либо предложения? Swift 4 - PullRequest
0 голосов
/ 07 мая 2019

Я новичок в 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: [])]
}

1 Ответ

0 голосов
/ 07 мая 2019

вы можете настроить ваши объекты в соответствии с протоколом 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")
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...