Swift 3 iOS10 core data check if record already exist base on id
A little tip, you can rewrite the following:
if results.count > 0 {
article = results.first as! Article
}else {
article = Article(context: context)
}
as:
let article = results.first as? Article ?? Article(context: context)
I assume you know how to create a and modify an object. For the missing exists
part, you could use something like this:
func someEntityExists(id: Int) -> Bool {
var fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "SomeEntity")
fetchRequest.predicate = NSPredicate(format: "someField = %d", id)
var results: [NSManagedObject] = []
do {
results = try managedObjectContext.fetch(fetchRequest)
}
catch {
print("error executing fetch request: \(error)")
}
return results.count > 0
}
The new and more efficient way of doing this would be using NSFetchRequestResult
.
func someEntityExists(id: Int) -> Bool {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "SomeEntity")
fetchRequest.includesSubentities = false
var entitiesCount = 0
do {
entitiesCount = try managedObjectContext.count(for: fetchRequest)
}
catch {
print("error executing fetch request: \(error)")
}
return entitiesCount > 0
}