我正在我的iOS应用中实现核心数据。我正在使用UICollectionView
。
我正在尝试在核心数据中插入用户收藏夹曲目。
点击我的UICollectionViewItems
中的图片(收藏夹)后的代码
@objc func addToFavouriteClicked(_ sender:UIButton){
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Favurites", in: context)
let favSong = NSManagedObject(entity: entity!, insertInto: context)
favSong.setValue(videos[sender.tag], forKey: "link")
favSong.setValue(titles[sender.tag], forKey: "title")
favSong.setValue(images[sender.tag], forKey: "image")
favSong.setValue(channels[sender.tag], forKey: "owner")
favSong.setValue("sender.tag", forKey: "id")
do {
try context.save()
} catch let err{
print("Failed saving",err.localizedDescription)
}
sender.setBackgroundImage(UIImage(named: "final2heart-outline-96"), for: .normal)
}
现在的问题是,如何检查收藏的商品数据是不是? 为此,我必须从UICollectionViewItems 获取所有记录?然后将每个项目的详细信息与核心数据记录进行匹配?
我该怎么做? 我尝试了一些破解,但没有成功。
这里是代码
func fetchAndUpdateFavorites(){
for i in 0..<collectionView.numberOfItems(inSection: 0) - 1{
let indexPath = IndexPath(row: i, section: 0)
DispatchQueue.main.async {
let cell = self.collectionView.cellForItem(at: indexPath) as! PlayerCollectionViewCell
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Favurites")
request.returnsObjectsAsFaults = false
do {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let result = try context.fetch(request)
for data in result as! [NSManagedObject] {
let id = data.value(forKey: "id") as! String
let url = data.value(forKey: "image") as! String
let titlee = data.value(forKey: "title") as! String
if id == "\(indexPath.row)" && url == self.images[indexPath.row] && titlee == self.titlesArr[indexPath.row] {
cell.addToFavouriteButton.setBackgroundImage(UIImage(named: "final2heart"), for: .normal)
print(data.value(forKey: "id") as! String,"Favourite")
}
}
} catch {
print("Failed")
}
}
}
}