如何在userdefault中存储和检索数据? (例如:结构数组)

时间:2019-05-21 12:10:05

标签: swift userdefaults

struct ExpandableNames:Codable {
    var isExpanded: Bool
    var names: [String]
    var icons: [String]
} 

var names = ["Food/Drink", "Tours", "Transport", "Gifts","Flights", "Shopping", "Activities","Entertainment","Accomodation","Other"]
var icons = ["Food_Category", "Tours", "Transport_Category", "Gifts_Category","Flights_Category","Shopping_Category","Activities_category","Entertainment_category", "Accomodation_Category","Other_Category"]

var categoryWholeArray = [Int:ExpandableNames]()

如何将categoryWholeArray存储为用户默认设置?

我尝试了

存储用户默认值:

 UserDefaults.standard.set(try? PropertyListEncoder().encode(categoryWholeArray), forKey:"categoryWholeArray")

在这里检索数据问题

   if let data = UserDefaults.standard.value(forKey:"categoryWholeArray") as? Data {
                      let songs2 = try? PropertyListDecoder().decode(Array<categoryWholeArray.values>.self, from: data)
}

有人尝试过吗?

2 个答案:

答案 0 :(得分:1)

在存储在encode中的同时,您需要UserDefaults数据,并且当您尝试获取这些数据时,必须decode

这是extension,我可以为您提供帮助。

extension UserDefaults {

    func setCustomObjToUserDefaults(CustomeObj: AnyObject, forKey:String) {
        let defaults = UserDefaults.standard
        let encodedData = NSKeyedArchiver.archivedData(withRootObject: CustomeObj)
        defaults.set(encodedData, forKey: forKey)
        defaults.synchronize()
    }

    func getCustomObjFromUserDefaults(forKey:String) -> AnyObject? {
        let defaults = UserDefaults.standard
        if defaults.object(forKey: forKey) != nil {
            if let decoded  = defaults.object(forKey: forKey) as? Data {
                let decodedTeams = NSKeyedUnarchiver.unarchiveObject(with:decoded) as AnyObject
                return decodedTeams
            }
        }
        return nil
    }

    func setJsonObject<T: Encodable>(encodable: T, forKey key: String) {
        if let data = try? JSONEncoder().encode(encodable) {
            set(data, forKey: key)
        }
    }

    func getJsonObject<T: Decodable>(_ type: T.Type, forKey key: String) -> T? {
        if let data = object(forKey: key) as? Data,
            let value = try? JSONDecoder().decode(type, from: data) {
            return value
        }
        return nil
    }

    func removeCustomObject(forKey:String)
    {
        let defaults = UserDefaults.standard
        defaults.removeObject(forKey: forKey)
        defaults.synchronize()
    }

}

答案 1 :(得分:-4)

所有正确的除外

if let data = UserDefaults.standard.value(forKey:"categoryWholeArray") as? Data {
    let songs2 = try? PropertyListDecoder().decode([Int:ExpandableNames].self, from: data)
    print(songs2)
}