在详细视图控制器中,用户可以将字符添加到收藏夹列表中。单击“收藏夹”按钮会将图像URL添加到CoreData。然后在集合视图控制器中,我运行以下代码:
override func viewDidLoad() {
super.viewDidLoad()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Favorite")
request.returnsObjectsAsFaults = false
do {
let results = try context.fetch(request)
if results.count > 0
{
for result in results as! [NSManagedObject]
{
if let favFig = result.value(forKey: "favFig") as? String
{
favFigArray.append(favFig)
}
if let favFigID = result.value(forKey: "favoriteID") as? String
{
favFigIDArray.append(favFigID)
}
}
}
} catch {
print("Error Fetching")
}
}
favFigArray然后包含图片网址列表。要将图像设置为我的集合视图单元格,我使用以下代码:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ownedCell", for: indexPath) as! OwnedCollectionViewCell
cell.ownedFigImage.sd_setImage(with: URL(string: favFigArray[indexPath.row]))
return cell
}
我遇到的问题是,当用户想要返回详细视图控制器并向收藏夹列表添加更多字符时,集合视图将不会更新。我尝试在viewWillAppear中使用self.ownedCollectionView.reloadData(),但这不起作用。 CoreData正在正确更新,但favFigArray未更新。
任何人都可以帮我重新加载吗?谢谢!
答案 0 :(得分:1)
您可以创建一种过滤结果的方法,如下所示
func filterFavFigData()
favFigArray.removeAll()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Favorite")
request.returnsObjectsAsFaults = false
do {
let results = try context.fetch(request)
if results.count > 0
{
for result in results as! [NSManagedObject]
{
if let favFig = result.value(forKey: "favFig") as? String
{
favFigArray.append(favFig)
}
if let favFigID = result.value(forKey: "favoriteID") as? String
{
favFigIDArray.append(favFigID)
}
}
}
} catch {
print("Error Fetching")
}
}
然后更新您的viewWillAppear
,如下所示
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.filterFavFigData()
self.ownedCollectionView.reloadData()
}