从 UserDefaults 快速保存和检索自定义对象

问题描述 投票:0回答:5

我在 Playground 中使用 Swift 3、Xcode 8.0:

import Foundation
class Person: NSObject, NSCoding {
    var name: String
    var age: Int
    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
    required convenience init(coder aDecoder: NSCoder) {
        let name = aDecoder.decodeObject(forKey: "name") as! String
        let age = aDecoder.decodeObject(forKey: "age") as! Int
        self.init(
            name: name,
            age: age
        )
    }
    func encode(with aCoder: NSCoder) {
        aCoder.encode(name, forKey: "name")
        aCoder.encode(age, forKey: "age")
    }
}

创建 Person 数组

let newPerson = Person(name: "Joe", age: 10)
var people = [Person]()
people.append(newPerson)

对数组进行编码

let encodedData = NSKeyedArchiver.archivedData(withRootObject: people)
print("encodedData: \(encodedData))")

保存到用户默认值

let userDefaults: UserDefaults = UserDefaults.standard()
userDefaults.set(encodedData, forKey: "people")
userDefaults.synchronize()

检查

print("saved object: \(userDefaults.object(forKey: "people"))")

从 userDefaults 中检索

if let data = userDefaults.object(forKey: "people") {
    let myPeopleList = NSKeyedUnarchiver.unarchiveObject(with: data as! Data)
    print("myPeopleList: \(myPeopleList)")
}else{
    print("There is an issue")
}

只需检查存档数据即可

if let myPeopleList = NSKeyedUnarchiver.unarchiveObject(with: encodedData){
   print("myPeopleList: \(myPeopleList)")
}else{
   print("There is an issue")
}

我无法正确地将数据对象保存到 userDefaults,此外,底部的检查会产生错误:

致命错误:在解包可选值时意外发现 nil

“检查”行还显示保存的对象为零。这是我对象的 NSCoder 中的错误吗?

ios swift xcode swift3 nscoding
5个回答
94
投票

Swift 4 或更高版本

您可以再次在 Playground 中保存/测试您的值


UserDefaults需要在实际项目中进行测试。注意:无需强制同步。如果您想在 Playground 中测试编码/解码,您可以使用键控存档器将数据保存到文档目录中的 plist 文件中。您还需要解决课堂上的一些问题:


class Person: NSObject, NSCoding {
    let name: String
    let age: Int
    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
    required init(coder decoder: NSCoder) {
        self.name = decoder.decodeObject(forKey: "name") as? String ?? ""
        self.age = decoder.decodeInteger(forKey: "age")
    }
    func encode(with coder: NSCoder) {
        coder.encode(name, forKey: "name")
        coder.encode(age, forKey: "age")
    }
}

测试:

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        do {
            // setting a value for a key
            let newPerson = Person(name: "Joe", age: 10)
            var people = [Person]()
            people.append(newPerson)
            let encodedData = try NSKeyedArchiver.archivedData(withRootObject: people, requiringSecureCoding: false)
            UserDefaults.standard.set(encodedData, forKey: "people")
            // retrieving a value for a key
            if let data = UserDefaults.standard.data(forKey: "people"),
                let myPeopleList = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? [Person] {
                myPeopleList.forEach({print($0.name, $0.age)})  // Joe 10
            }                    
        } catch {
            print(error)
        }
        
    }
}

49
投票
let age = aDecoder.decodeObject(forKey: "age") as! Int

这已针对 Swift 3 进行了更改;这不再适用于值类型。现在正确的语法是:

let age = aDecoder.decodeInteger(forKey: "age")

各种不同类型都有关联的decode...()函数:

let myBool = aDecoder.decodeBoolean(forKey: "myStoredBool")
let myFloat = aDecoder.decodeFloat(forKey: "myStoredFloat")

编辑:Swift 3中所有可能的decodeXXX函数的完整列表

编辑:

另一个重要注意事项:如果您之前保存过使用旧版本 Swift 编码的数据,则这些值必须使用decodeObject()进行解码,但是一旦您使用encode(...)重新编码数据如果它是值类型,则无法再使用decodeObject()对其进行解码。因此,Markus Wyss 的答案将允许您处理使用任一 Swift 版本对数据进行编码的情况:

self.age = aDecoder.decodeObject(forKey: "age") as? Int ?? aDecoder.decodeInteger(forKey: "age")

22
投票

在 Swift 4 中:

您可以使用 Codable 从用户默认值中保存和检索自定义对象。如果您经常这样做,那么您可以添加为扩展并像下面一样使用它。

extension UserDefaults {

   func save<T:Encodable>(customObject object: T, inKey key: String) {
       let encoder = JSONEncoder()
       if let encoded = try? encoder.encode(object) {
           self.set(encoded, forKey: key)
       }
   }

   func retrieve<T:Decodable>(object type:T.Type, fromKey key: String) -> T? {
       if let data = self.data(forKey: key) {
           let decoder = JSONDecoder()
           if let object = try? decoder.decode(type, from: data) {
               return object
           }else {
               print("Couldnt decode object")
               return nil
           }
       }else {
           print("Couldnt find key")
           return nil
       }
   }

}

您的课程必须遵循 Codable。它只是可编码和可解码协议的类型别名。

class UpdateProfile: Codable {
  //Your stuffs
}

用途:

let updateProfile = UpdateProfile()

//To save the object
UserDefaults.standard.save(customObject: updateProfile, inKey: "YourKey")

//To retrieve the saved object
let obj = UserDefaults.standard.retrieve(object: UpdateProfile.self, fromKey: "YourKey")

有关更多编码和解码自定义类型,请参阅Apple 文档

Swift 5 新解决方案

使用属性包装器+组合可测试用户默认值

@propertyWrapper struct UserDefaultsStore<T: Codable> {
    let key: String
    let storage: UserDefaultsStorage
    private let subject: PassthroughSubject<[T], Never> = .init()
    
    var wrappedValue: [T] {
        get {
            guard let data = storage.object(forKey: key) as? Data,
               let models = try? JSONDecoder().decode([T].self, from: data) else {
                return []
            }
            return models
           
        }
        set {
            if let encoded = try? JSONEncoder().encode(newValue) {
                storage.set(encoded, forKey: key)
                subject.send(wrappedValue)
            }
            
        }
    }
    
    var projectedValue: AnyPublisher<[T], Never> {
        return subject.eraseToAnyPublisher()
    }
}

protocol UserDefaultsStorage {
    func object(forKey key: String) -> Any?
    func set(_ value: Any?, forKey key: String)
}

extension UserDefaults: UserDefaultsStorage {}

struct DataToSave: Codable {}



//Usage
// Main Target
enum StorageSettings {
    @UserDefaultsStore<DataToSave>(key:"stored_locations", storage: DIInjecter.userDefaults)
    static var storeSomething: [DataToSave]
    
}
struct DependenciesInjecter {
    lazy var userDefaults: UserDefaultsStorage = UserDefaults.standard
}
var DIInjecter = DependenciesInjecter()

// Test Target
class UserDefaultsStorageMock: UserDefaultsStorage {
    var values: [String: Any]
    init(values: [String : Any] = [:]) {
        self.values = values
    }

    func object(forKey key: String) -> Any? {
        return values[key]
    }

    func set(_ value: Any?, forKey key: String) {
        values[key] = value
    }
}

extension DependenciesInjecter {
    static var mock: DependenciesInjecter {
        Self(userDefaults: UserDefaultsStorageMock())
    }
}
// Put it in setup func
DIInjecter = .mock

12
投票

试试这个:

self.age = aDecoder.decodeObject(forKey: "age") as? Int ?? aDecoder.decodeInteger(forKey: "age")

4
投票

在 Swift 5 中,我会使用属性包装器来简化代码:

/// A type that adds an interface to use the user’s defaults with codable types
///
/// Example:
/// ```
/// @UserDefaultCodable(key: "nameKey", defaultValue: "Root") var name: String
/// ```
/// Adding the attribute @UserDefaultCodable the property works reading and writing from user's defaults
/// with any codable type
///
@propertyWrapper public struct UserDefaultCodable<T: Codable> {
    private let key: String
    private let defaultValue: T

    /// Initialize the key and the default value.
    public init(key: String, defaultValue: T) {
        self.key = key
        self.defaultValue = defaultValue
    }

    public var wrappedValue: T {
        get {
            // Read value from UserDefaults
            guard let data = UserDefaults.standard.object(forKey: key) as? Data else {
                // Return defaultValue when no data in UserDefaults
                return defaultValue
            }

            // Convert data to the desire data type
            let value = try? JSONDecoder().decode(T.self, from: data)
            return value ?? defaultValue
        }
        set {
            // Convert newValue to data
            let data = try? JSONEncoder().encode(newValue)

            // Set value to UserDefaults
            UserDefaults.standard.set(data, forKey: key)
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.