如何保存实现Codable的自定义对象

时间:2017-06-12 09:23:19

标签: ios swift swift4

现在,Swift 4可以更轻松地对JSON or Properties list进行编码/解码。

但我无法使用Codable找到如何使用Codable编码,而不使用Objective-C方法 DispatchQueue.global().async { let timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(self.MyFunction), userInfo: nil, repeats: false) RunLoop.current.add(timer, forMode: .defaultRunLoopMode) RunLoop.current.run() } initWithCoder

考虑这个简单的课程:

encodeWithCoder

如何使用struct Question: Codable { var title: String var answer: Int var question: Int } 而不是CodingKeysinitWithCoder将其编码为数据?

编辑: 我还需要能够使用NSKeyedArchiver对先前保存在userdefaults中的对象进行反序列化。

4 个答案:

答案 0 :(得分:26)

好吧,你不再需要NSKeyedArchiver

试试这个:

let questionObj = Question(title: "WWDC, 2017", answer: 1,question:1)
let encoder = JSONEncoder()
if let encoded = try? encoder.encode(questionObj) {
    UserDefaults.standard.set(encoded, forKey: "K_Question")
}
let decoder = JSONDecoder()
if let questionData = UserDefaults.standard.data(forKey: "K_Question"),
    let question = try? decoder.decode(Question.self, from: questionData) {
    print(question.title)
    print(question.answer)
    print(question.question)
}

答案 1 :(得分:3)

Swift 5 UserDefaults 的一个非常简单的扩展:

extension UserDefaults {

    func save<T: Codable>(_ object: T, forKey key: String) {
        let encoder = JSONEncoder()
        if let encodedObject = try? encoder.encode(object) {
            UserDefaults.standard.set(encodedObject, forKey: key)
            UserDefaults.standard.synchronize()
        }
    }

    func getObject<T: Codable>(forKey key: String) -> T? {
        if let object = UserDefaults.standard.object(forKey: key) as? Data {
            let decoder = JSONDecoder()
            if let decodedObject = try? decoder.decode(T.self, from: object) {
                return decodedObject
            }
        }
        return nil
    }
}

用法

保存

UserDefaults.standard.save(currentUser, forKey: "currentUser")

获取

let user: User? = UserDefaults.standard.getObject(forKey: "currentUser")

答案 2 :(得分:0)

可以通过JSONEncoder和JSONDecoder实现。

MYFCN_H

答案 3 :(得分:0)

struct Question: Codable {
    var title: String
    var answer: Int
    var question: Int
}

class UserDefaults_Question {
    static let key = "myapp.trick.question"

    static var value: UserDefaults_Question? {
        get {
            guard let data = UserDefaults.standard.data(forKey: key) else {
                print("no model for key: \(key)")
                return nil
            }
            guard let model = try? JSONDecoder().decode(UserDefaults_Question.self, from: data) else {
                print("failed to decode model for key: \(key)")
                return nil
            }
            print("did load model for key: \(key)")
            return model
        }
        set {
            guard let value = newValue, let data: Data = try? JSONEncoder().encode(value) else {
                print("removing model for key: \(key)")
                UserDefaults.standard.removeObject(forKey: key)
                return
            }
            print("inserting model for key: \(key)")
            UserDefaults.standard.set(data, forKey: key)
        }
    }
}

UserDefaults_Question.value = Question(title: "Next President", answer: 666, question: -1)