Reputation: 5
I have a single entity Favourites
and it contains values such as id
, name
but the problem is that it is creating multiple copies of items and I wanted it to only store values if it is unique. How can I do this with Core Data?
Here is my code:
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let newFav = Favourites(context: context)
if let id = self.itemsViewModel.items?.results?[indexPath.item].id {
newFav.id = id
}
if let name = self.itemsViewModel.items?.results?[indexPath.item].name {
newFav.name = name
}
self.saveItem()
I do this in an alert and outside of that closure is my saveItem() function everything works but I am trying to save only one item with one id. I am thinking of checking if that id
exists but I am not quite sure how would I do that with CoreData
func saveItem() {
do {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
try context.save()
} catch {
print("Error saving context \(error)")
}
}
Upvotes: 0
Views: 1743
Reputation: 285079
Perform a fetch with a distinct predicate and create a new record if the result is zero, for example
func saveItem(with id : Int32, name : String) {
do {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let request : NSFetchRequest<Favourites> = Favourites.fetchRequest()
request.predicate = NSPredicate(format: "id == %d AND name == %@", id, name)
let numberOfRecords = try context.count(for: request)
if numberOfRecords == 0 {
let newFav = Favourites(context: context)
newFav.name = name
newFav.id = id
try context.save()
}
} catch {
print("Error saving context \(error)")
}
}
Upvotes: 1