Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Garut

macrumors newbie
Original poster
Sep 7, 2021
6
0
I am building an app and it relies on Core Data to save and retrieve my hockey favourites. The issue I have is with retrieving. I don't understand why it retrieves all the players multiple times until you can't add any more favourites. It should retrieve only the players you favourite not all of them multiple times. Any help would be greatly appreciated.



Swift:
override func viewWillAppear(_ animated: Bool) {


        super.viewWillAppear(animated)


        let fetchRequest = NSFetchRequest<CurrentPlayers>(entityName: "CurrentPlayers")


        do {


            prefArr = try context.fetch(fetchRequest)


            for p in prefArr {


                if p.yahooName == "Carey Price" {


                    print("Carey added")


                }


            }


            print("There are this many saved favourites \(prefArr.count)")


        } catch let error {


            print("Could not fetch. \(error)")


        }


    }

Swift:
@IBAction func save(_ sender: UIBarButtonItem) {


        let entity = NSEntityDescription.entity(forEntityName: "CurrentPlayers", in: context)!


        let saveFav = CurrentPlayers(entity: entity, insertInto: context)


        for o in prefArr {


            saveFav.yahooName = o.yahooName


            saveFav.team = o.team


            saveFav.position = o.position


            saveFav.photoUrl = o.photoUrl


        do {


            try context.save()


            print("These are my saved objects: \(saveFav)")


            print("how many saved objects: \(prefArr.count)")


        } catch {


            print("error is:  \(error)")


        }


        }

}
    }
 

szymczyk

macrumors regular
Mar 5, 2006
187
17
Your fetch request code

Swift:
let fetchRequest = NSFetchRequest<CurrentPlayers>(entityName: "CurrentPlayers")

Fetches every CurrentPlayers entity. To fetch only the favorites you must configure the fetch request with a predicate to fetch only the favorites.

You have not provided any code or information on how a player becomes a favorite so I cannot provide a more specific answer. Is the favorite an attribute of the CurrentPlayers entity? Is the favorite a separate entity? Providing this information will help anyone reading this give you a more specific answer.
 
  • Like
Reactions: GorillaPaws

Garut

macrumors newbie
Original poster
Sep 7, 2021
6
0
I add favourites in another class called FavouriteManager.



Swift:
class FavouriteManager {


    


    


    static let shared = FavouriteManager()


    


    var favArr : [CurrentPlayers] = []


    





    


    func add(_ player: CurrentPlayers) {


        NotificationCenter.default.post(


            name: .passFavNotification,


            object: player


        )


        


        favArr.append(player)


        


        for player in favArr {


            if !favArr.contains(player) {


                favArr.append(player)


            }


    }


}


}



A player becomes a favourite when the user taps a heart button in another VC called HockeyDetailVC



Swift:
@IBAction func addToFav(_ sender: Any) {


               let alert = UIAlertController(title: "Favourite Added ?", message: "\(name.text ?? "") is added to favourites", preferredStyle: .alert)


               alert.addAction(UIAlertAction(


                    title: "OK",


                    style: UIAlertAction.Style.default)


               { [self]  _ in

                //item is the player object to be added into favourites
                FavouriteManager.shared.add(item!)


                    })


               self.present(alert, animated: true, completion: nil)


           }


In my favourites VC where I view all my favourites I have an array called


Swift:
var prefArr: Array<CurrentPlayers> {


        get { FavouriteManager.shared.favArr }


        set { FavouriteManager.shared.favArr = newValue }


    }
 

szymczyk

macrumors regular
Mar 5, 2006
187
17
Instead of having a FavoritesManager, add a Boolean attribute to the CurrentPlayers entity that stores whether the player is a favorite. When someone taps the heart button, set the favorite attribute to true. To retrieve the favorites, do a fetch request on the players where the favorite attribute is true.
 
  • Like
Reactions: GorillaPaws

Garut

macrumors newbie
Original poster
Sep 7, 2021
6
0
I'm not sure how to do it without FavouriteManager but I did what you asked but I have an issue deleting the cells the saved favourites keep coming back even when I deleted them. Is there a way to modify the delete function to counter that.


//delete function
Swift:
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {


    if editingStyle == .delete {


        tableView.beginUpdates()


        prefArr.remove(at: indexPath.row)


        tableView.deleteRows(at: [indexPath], with: .fade)


        tableView.endUpdates()


      }


     }
 

szymczyk

macrumors regular
Mar 5, 2006
187
17
You haven't shown the code where you save prefArr. Nothing in your FavoritesManager code is using Core Data. How are you saving that array? Are you using Core Data to save the list of favorites? Show your CurrentPlayer entity, its attributes, and any relationships. How are you modeling the favorites in Core Data?

In Core Data when you delete an instance of the entity, you must save the context for the delete to take effect.
 

Garut

macrumors newbie
Original poster
Sep 7, 2021
6
0
You haven't shown the code where you save prefArr.

I think I did in the beginning of the post with the save button.

Swift:
@IBAction func save(_ sender: UIBarButtonItem) {


        let entity = NSEntityDescription.entity(forEntityName: "CurrentPlayers", in: context)!


        let saveFav = CurrentPlayers(entity: entity, insertInto: context)


        for o in prefArr {


            saveFav.yahooName = o.yahooName


            saveFav.team = o.team


            saveFav.position = o.position


            saveFav.photoUrl = o.photoUrl

            o.isFavourite = true


        do {


            try context.save()


            print("These are my saved objects: \(saveFav)")


            print("how many saved objects: \(prefArr.count)")


        } catch {


            print("error is:  \(error)")


        }


        }

}
    }

Nothing in your FavoritesManager code is using Core Data. How are you saving that array? Are you using Core Data to save the list of favorites?

Nothing in there your right but in my FavouritesVC I have core data and I have my save button to save them.

Show your CurrentPlayer entity, its attributes, and any relationships. How are you modeling the favorites in Core Data?

This is my CoreData properties file hope this helps

Swift:
import Foundation


import CoreData








extension CurrentPlayer {





    @nonobjc public class func fetchRequest() -> NSFetchRequest<CurrentPlayer> {


        return NSFetchRequest<CurrentPlayer>(entityName: "CurrentPlayer")


    }





    @NSManaged public var firstName: String?


    @NSManaged public var jerseyNumber: Int64


    @NSManaged public var lastName: String?


    @NSManaged public var photoUrl: String?


    @NSManaged public var position: String?


    @NSManaged public var status: String?


    @NSManaged public var team: String?


    @NSManaged public var yahooName: String?


    @NSManaged public var isFavourite: Bool





}

I still have trouble trying to delete one of my saved favourites. This is the code of my modified delete function.


Swift:
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {


    if editingStyle == .delete {


        tableView.beginUpdates()


        prefArr.remove(at: indexPath.row)


        tableView.deleteRows(at: [indexPath], with: .fade)


        PersistenceService.saveContext()


        tableView.endUpdates()


      }


     }
]

update: Just wanted to mention I changed the entity name from CurrentPlayers to CurrentPlayer
 
Last edited:
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.