gpt4 book ai didi

ios - 在 Swift 中,如何检测编码的自定义类数组中的重复项?

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

我有一个数组,用于存储已编码的自定义类,以便可以将其保存到 NSUserDefaults 中。它基于带有收藏夹按钮的 tableView 单元格,每次按下收藏夹按钮时,它都会保存到本地数组,然后保存到 NSUserDefaults。问题是,如果多次按下收藏夹按钮,该 tableView 单元格的多个副本将被保存到 NSUserDefaults 中。这是我保存数据的代码。我尝试检查“savedFavorite”是否已存在于数组中,但由于它每次都被编码为不同的编码值,因此它看起来不像重复的:

 let myDefaults = NSUserDefaults.standardUserDefaults()
let savedShow1 = "savedShow1"
var savedFavorite: TvShowInfo!
var savedFavoriteArray:[TvShowInfo] = []

@IBAction func saveShow(sender: UIButton) {

//accessing current point of tableView Cell
let location: CGPoint = sender.convertPoint(CGPointZero, toView: self.tvShowTableView)
let indexPath: NSIndexPath = self.tvShowTableView.indexPathForRowAtPoint(location)!
let searchTermsData = myDefaults.objectForKey(savedShow1) as? NSData

//accessing previously saved info so as not to overwrite it
if searchTermsData?.length > 0 {
let searchTermsArray = NSKeyedUnarchiver.unarchiveObjectWithData(searchTermsData!) as? [TvShowInfo]

self.savedFavoriteArray = searchTermsArray!
}

if searchBarActive {
savedFavorite = filteredShowSearchResults[indexPath.row]
} else {
savedFavorite = showArray[indexPath.row]
}

if savedFavoriteArray.contains(savedFavorite) {
print("Item already in array")
} else {
savedFavoriteArray.append(savedFavorite)
}

let savedData = NSKeyedArchiver.archivedDataWithRootObject(savedFavoriteArray)
myDefaults.setObject(savedData, forKey: savedShow1)
myDefaults.synchronize()
}

这是我的自定义类:

class TvShowInfo: NSObject, NSCoding {

var poster: String
var title: String
var id: NSNumber

init(poster: String, title: String, id: NSNumber) {

self.poster = poster
self.title = title
self.id = id

}

// MARK: - comply wiht NSCoding protocol

func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(poster, forKey: "poster")
aCoder.encodeObject(title, forKey: "title")
aCoder.encodeObject(id, forKey: "id")
}

required convenience init?(coder aDecoder: NSCoder) {

// decoding could fail, for example when no Blog was saved before calling decode
guard let unarchivedPoster = aDecoder.decodeObjectForKey("poster") as? String,
let unarchivedTitle = aDecoder.decodeObjectForKey("title") as? String,
let unarchivedId = aDecoder.decodeObjectForKey("id") as? NSNumber

else {
// option 1 : return an default Blog
self.init(poster: "unkown", title:"unkown", id: 0)
return
}

// convenience init must call the designated init
self.init(poster: unarchivedPoster, title: unarchivedTitle, id: unarchivedId)
}
}

最佳答案

您还可以将数组转换为集合(NSSet),并且您的数组将立即消除重复项。参见这篇文章:Set operations (union, intersection) on Swift array?

关于ios - 在 Swift 中,如何检测编码的自定义类数组中的重复项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36163694/

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