简体   繁体   English

将结构数组保存到userDefaults

[英]Saving an array of structs to userDefaults

In my app I have the user take a picture of an item of clothing, then give it a tag describing what type it is (pants, shirt, shoes, etc). 在我的应用程序中,我让用户为一件衣服拍照,然后给它添加一个标签来描述它是什么类型(裤子,衬衫,鞋子等)。 I then take this info and save it into a struct Item. 然后,我获取此信息并将其保存到结构项中。 After that, I put the recently made Item into an array of Items. 之后,我将最近制作的Item放入Items数组中。 I'm struggling with how to save this array of Items to UserDefaults so I can load back when the app is closed. 我在如何将此项目数组保存到UserDefaults上感到挣扎,以便在应用程序关闭时可以重新加载。

I've tried adding Codable to my struct but that just brought up more issues. 我尝试将Codable添加到我的结构中,但这带来了更多问题。 I wanted to update the UserDefaults every time the user adds a new item to the array. 每当用户向阵列中添加新项目时,我都想更新UserDefaults。 I plan to do it in saveItemButton function (shown below). 我计划在saveItemButton函数中执行此saveItemButton (如下所示)。

var itemsArray: [Item] = []

//.pants, .shirt, .shoes, .hat, .extra, .jacket
var itemType: clothingType? = nil

@IBAction func saveItemButton(_ sender: Any) {
    if(itemType != nil && imageView.image != nil){
        saveImage(imageName: ("item" + "\(itemsArray.count)"))
        let item = Item(itemType: itemType!, itemName: ("item" + "\(itemsArray.count)"))


        itemsArray.append(item)

        //let defaults = UserDefaults.standard
        //defaults.set(itemsArray, forKey: "SavedItemArray")
    }
}

Here is my struct in a separate swift file: 这是我在单独的swift文件中的结构:

import Foundation
import UIKit


struct Item{
    var itemType: clothingType
    var itemName: String
    //var itemImage: UIImage?
}

enum clothingType{
    case pants
    case shirt
    case jacket
    case shoes
    case hat
    case extra
}

And here is where I would load the itemArray from UserDefaults: 这是我从UserDefaults加载itemArray的位置:

override func viewDidLoad() {
    super.viewDidLoad()
    //        let defaults = UserDefaults.standard
    //        let array = defaults.array(forKey: "SavedItemArray")  as? [Item] ?? [Item]()
    //        itemsArray = array
}

Looking to be able to save and load an array of Item to UserDefaults. 希望能够将Item数组保存并加载到UserDefaults。

Like this: 像这样:

struct Item : Codable {
    var itemType: clothingType
    var itemName: String
}

enum clothingType : String, Codable {
    case pants
    case shirt
    case jacket
    case shoes
    case hat
    case extra
}

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let defaults = UserDefaults.standard
        if let data = defaults.data(forKey: "SavedItemArray") {
            let array = try! PropertyListDecoder().decode([Item].self, from: data)
        }
    }
}

Of course I suppose now you're wondering how we got the data into user defaults in the first place. 当然,我想现在您想知道我们如何首先将数据转换为用户默认值。 Like this: 像这样:

    let array : [Item] = // whatever
    if let data = try? PropertyListEncoder().encode(array) {
        UserDefaults.standard.set(data, forKey: "SavedItemArray")
    }

As @rmaddy comment says 正如@rmaddy评论所说

Saving those kind of data into the UserDefault is not recommended 不建议将这类数据保存到UserDefault

however technically let's say you're going to save those however you like, UserDefault don't accept this type of structure, what you need to do is converting this array to type Data saving it into the UserDefault then fetch it as Data then cast it back to it's original form, but again this is not recommended. 但是从技术上说,您要保存那些您喜欢的东西, UserDefault不接受这种类型的结构,您需要做的是将该数组转换为Data类型,将其保存到UserDefault ,然后将其提取为Data然后进行转换回到其原始形式,但再次不建议这样做。

Read more about it here . 在此处了解更多信息。

Also hitting search on this 也点击搜索

what is user defaults for swift ? swift的用户默认设置是什么?

Will give you the answer of this 会给你答案

The user defaults is a .plist file in your app's package and you can use it to set and get simple pieces of data . 用户默认值为应用程序包中的.plist文件,您可以使用它来设置和获取简单的数据 It's structure is very similar to that of a dictionary and the user defaults are often regarded as a key-value store . 它的结构与字典非常相似,并且用户默认值通常被视为键值存储。

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

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