gpt4 book ai didi

swift - 如何使用 UserDefaults 保存包含已创建类的信息的数组

转载 作者:行者123 更新时间:2023-11-30 12:30:58 27 4
gpt4 key购买 nike

我创建了一个应用程序,用于向用户展示最新和顶级的乡村歌曲。我使用 Firebase 数据库发送和接收歌曲信息。这是在 Xcode 中使用 Swift 和 UIKit 实现的。

我创建了一个名为 Song 的类,用于处理从 Firebase 获取的所有信息。该类在下面。

import Foundation
import UIKit

class Song {

//private var _imageURL: String!
private var _videoURL: NSMutableURLRequest!
private var _songTitle: String!
private var _artistName: String!
private var _cellNum: Int!
private var _lastNum: Int!
private var _spotifyLink: String!
private var _itunesLink: String!
private var _lyrics: String!
private var _saved: Bool!

// var imageURL: String{
// return _imageURL
// }

var videoURL: NSMutableURLRequest{
return _videoURL
}

var songTitle: String{
return _songTitle
}

var artistName: String{
return _artistName
}

var cellNum: Int{
return _cellNum
}

var lastNum: Int{
return _lastNum
}

var spotifyLink: String{
return _spotifyLink
}

var itunesLink: String{
return _itunesLink
}

var lyrics: String{
return _lyrics
}

var saved: Bool{
get{
return _saved
}
set{
_saved = newValue
}
}

init(videoURL: NSMutableURLRequest, songTitle: String, artistName: String, cellNum: Int, lastNum: Int, spotifyLink: String, itunesLink: String, lyrics: String, saved: Bool) {

//_imageURL = imageURL
_videoURL = videoURL
_songTitle = songTitle
_artistName = artistName
_cellNum = cellNum
_lastNum = lastNum
_spotifyLink = spotifyLink
_itunesLink = itunesLink
_lyrics = lyrics
_saved = saved
}
}

在我的一个 swift 文件中,我初始化了一个 Song 类型的新数组来保存用户保存的信息。

var savedSongs = [Song]()

其中一个 Storyboard中有一个按钮,如果用户单击它,则会将保存的歌曲添加到数组中,并且当用户转到 SavedVC Storyboard时,会显示数组中保存的所有项目用户。点击按钮的函数如下所示。

@IBAction func save(_ sender: Any) {


if(saveBtn.currentTitle == "Save"){

song.saved = true
let p1 = song
savedSongs.append(p1)
//UserDefaults save here
saveBtn.setTitle("Unsave", for: .normal)
}
else if(saveBtn.currentTitle == "Unsave"){

if(savedSongs.count != 0){
//let items = (savedSongs.count) - 1

let title = song.songTitle

for save in 0...savedSongs.count-1{

let removeSave = savedSongs[save]
let checkTitle = removeSave.songTitle

if(checkTitle == title){
song.saved = false
savedSongs.remove(at: save)
//UserDefaults save here
saveBtn.setTitle("Save", for: .normal)
return
}
}
}
}
}

很明显,用户可以选择保存,之后,他可以重新单击按钮来取消保存歌曲。在代码中,对象

song.(attribute)

被发送,是所选单元格的表示形式,其中包含 Song 类的信息。由于我现在有代码,所以一切正常。问题是,当我离开应用程序时,数组中的内容不会保留。我已经尝试过 UserDefaults,但我不确定如何使用我拥有的数组来做到这一点。

每次在上面的保存 IBAction 中单击按钮时,我都希望将数组保存为用户默认值。

最佳答案

您需要对对象进行编码和解码,以便将它们保存到 UserDefaults。

class Song: NSObject, NSCoding {
let name: String
let url: String

init(name: String, url: String) {
self.name = name
self.url = url
}

required init(coder decoder: NSCoder) {
self.name = decoder.decodeObject(forKey: "name") as? String ?? ""
self.url = decoder.decodeInteger(forKey: "url") as? String ?? ""
}

func encode(with coder: NSCoder) {
coder.encode(name, forKey: "name")
coder.encode(age, forKey: "url")
}
}

然后检索并保存:

class MyViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// SAVE TO DEFAULTS
let song = Song(name: "Song", url: "http://song.com")
var songs = [Song]()
songs.append(song)
let encodedData = NSKeyedArchiver.archivedData(withRootObject: songs)
UserDefaults.standard.set(encodedData, forKey: "songs")

// RETRIEVE FROM DEFAULTS
if let data = UserDefaults.standard.data(forKey: "songs"),
let mySongs = NSKeyedUnarchiver.unarchiveObject(with: data) as? [Song] {
mySongs.forEach({print( $0.name, $0.url)})
} else {
print("ERROR")
}
}
}

关于swift - 如何使用 UserDefaults 保存包含已创建类的信息的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43565198/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com