Sunday, May 17, 2026
HomeiOS Developmentios - SwiftUI: Saving likes in CoreData for every particular person cell

ios – SwiftUI: Saving likes in CoreData for every particular person cell

[ad_1]

world! How do I save the like state for every particular person cell? I made a decision to avoid wasting through CoreData, however the like is saved for all cells directly.

Within the Core Information mannequin (LikedDB) there may be an attribute comparable to isLiked

Within the class there’s a variable isLiked, which adjustments the state of the like:

class ModelsViewModel: ObservableObject{
@Revealed var isLiked = false

func like() {
        isLiked.toggle()
    }
}

That is how I save the like state from ModelsViewModel
And in label I exploit

struct CellView: View{
    
    //For like
    @ObservedObject var cellViewModel: ModelsViewModel = ModelsViewModel()
    
    init(cardData: Mannequin) {
        self.cellViewModel.card = cardData
    }

    var physique: some View{

        Button(motion: {
        let likedDBE = LikedDBE(context: self.managedObjectContext)
        likedDBE.isLiked = cellViewModel.isLiked //I point out that isLiked from CoreData = isLiked from ModelsViewModel()

        do{
            cellViewModel.like() //func from ModelsViewModel()
            attempt self.managedObjectContext.save() //Save
        } catch{
            print(error)
        }

        }, label: {
        Picture(systemName: cellViewModel.isLiked ? "coronary heart.fill" : "coronary heart") //Right here I exploit
           .body(width: 22, peak: 22)
           .foregroundColor(cellViewModel.isLiked ? .crimson : .black) //And right here I exploit
})

And if I exploit cellViewModel.isLiked, then once I click on like, the like is displayed solely on the one I clicked on, however the state will not be saved when restarting the appliance, if I exploit likedDB.isLiked, then the like is displayed on all cells directly, however the like is saved after restarting.

I need the wish to be solely on the cell I clicked on and it is going to be saved after restarting the appliance.

[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments