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)")
}
}
}
}