简体   繁体   English

在UserDefaults中保存对象数组

[英]Saving an array of objects in UserDefaults

Using swift 3.0, I'm trying to add an array of objects into user defaults. 使用Swift 3.0,我试图将一组对象添加到用户默认设置中。 As this isn't one of the regular UserDefault types I've realised that the object or array of objects (can't work out which one) will need to be parsed to the type NSData to then be added to UserDefaults. 由于这不是常规的UserDefault类型之一,因此我意识到需要将对象或对象数组(无法算出哪一个)解析为NSData类型,然后再添加到UserDefaults中。

My attempt so far is the following: 到目前为止,我的尝试如下:

Within the object 在对象内

func updateDefaults()
{
    let data = NSData(data: MyVariables.arrayList)
    UserDefaults.standard.set(data, forKey: "ArrayList")
}

Where MyVariables.arrayList is the array of objects. 其中MyVariables.arrayList是对象数组。

Lastly, if possible it would be nice to know how to retrieve this from UserDefaults and convert it to the original one-dimensional array of objects. 最后,如果可能的话,很高兴知道如何从UserDefaults中检索此值并将其转换为对象的原始一维数组。

Thanks 谢谢

REPOSITORY: https://github.com/Clisbo/ModularProject 仓库: https : //github.com/Clisbo/ModularProject

You can't save your custom array in NSUserDefaults. 您无法将自定义数组保存在NSUserDefaults中。 To do that you should change them to NSData then save it in NSUserDefaults Here is the code. 为此,您应该将它们更改为NSData,然后将其保存在NSUserDefaults中。这是代码。

var custemArray: [yourArrayType] {
    get {
        if let data = NSUserDefaults.standardUserDefaults().objectForKey("yourKey") as? NSData {
           let myItem = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? yourType
        }
    }
    set {
        let data =NSKeyedArchiver.archivedDataWithRootObject(yourObject);
        NSUserDefaults.standardUserDefaults().setObject(data, forKey: "yourKey")
        NSUserDefaults.standardUserDefaults().synchronize()
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM