Coredata relationship issue

后端 未结 2 569
Happy的楠姐
Happy的楠姐 2021-01-27 11:44

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

2条回答
  •  悲哀的现实
    2021-01-27 12:27

    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
        }
    

提交回复
热议问题