I\'m facing a weird issue with my core data. I\'ve the following relationship
A contact can belong to one category and a category can have multiple contacts. I\'d like
The category
property of a Contact
object is a Category
object. But you are trying to set it to be a String (categoryField.text
). You probably want to use a Category
object whose name
is equal to categoryField.text
.
You could create one:
let categoryEntity = NSEntityDescription.entityForName("Category", inManagedObjectContext: context!)
let newCategory = Category(entity: categoryEntity!, insertIntoManagedObjectContext: context)
newCategory.name = categoryField.text
// set the other properties for the Category as necessary
// then assign the relationship
newContact.category = newCategory
But you might already have created a Category
with that name
. So the usual approach would be to search for a Category with the right name
, use that if it exists, or create a new Category if not:
let categoryEntity = NSEntityDescription.entityForName("Category", inManagedObjectContext: context!)
let fetchRequest = NSFetchRequest()
fetchRequest.entity = categoryEntity!
fetchRequest.predicate = NSPredicate(format:"name == %@",categoryField.text)
let fetchResults = try? context!.executeFetchRequest(fetchRequest)
if let results = fetchResults {
var requiredCategory : Category
if (results.count > 0) {
requiredCategory = results[0] as! Category
} else {
requiredCategory = Category(entity: categoryEntity!, insertIntoManagedObjectContext: context!)
requiredCategory.name = categoryField.text
// set the other properties for the Category as necessary
}
newContact.category = requiredCategory
}