将结构保存到用户默认值 [英] Save Struct to UserDefaults

查看:29
本文介绍了将结构保存到用户默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要保存到 UserDefaults 的结构.这是我的结构

I have a struct that I want to save to UserDefaults. Here's my struct

struct Song {
    var title: String
    var artist: String
}

var songs: [Song] = [
    Song(title: "Title 1", artist "Artist 1"),
    Song(title: "Title 2", artist "Artist 2"),
    Song(title: "Title 3", artist "Artist 3"),
]

在另一个 ViewController 中,我有一个 UIButton 附加到这个结构中

In another ViewController, I have a UIButton that appends to this struct like

@IBAction func likeButtonPressed(_ sender: Any) {   
   songs.append(Song(title: songs[thisSong].title, artist: songs[thisSong].artist))
}

我想要它,以便每当用户单击该按钮时,它也会将结构保存到 UserDefaults,这样每当用户退出应用程序然后再次打开它时,它就会被保存.我该怎么做?

I want it so that whenever the user clicks on that button also, it saves the struct to UserDefaults so that whenever the user quits the app and then opens it agian, it is saved. How would I do this?

推荐答案

在 Swift 4 中,这几乎是微不足道的.只需将结构标记为采用 Codable 协议,即可使您的结构可编码:

In Swift 4 this is pretty much trivial. Make your struct codable simply by marking it as adopting the Codable protocol:

struct Song:Codable {
    var title: String
    var artist: String
}

现在让我们从一些数据开始:

Now let's start with some data:

var songs: [Song] = [
    Song(title: "Title 1", artist: "Artist 1"),
    Song(title: "Title 2", artist: "Artist 2"),
    Song(title: "Title 3", artist: "Artist 3"),
]

以下是如何将其放入 UserDefaults:

Here's how to get that into UserDefaults:

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

这里是稍后再次取回它的方法:

And here's how to get it back out again later:

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

这篇关于将结构保存到用户默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆