Coredata relationship issue

后端 未结 2 568
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:26

    The answer is in your error:

    Cannot assign a value of type 'String!' to a value of type 'Category'

    The error is saying, that your category property in Contact class is defined to hold Category type object rather than an instance of NSString.

    So you need to assign an object of type Category, something like this:

    Create new category, or get an existing category by any means, here we'll create new category and assign that to the contact.

    let catEntity = NSEntityDescription.entityForName("Category", inManagedObjectContext: context!)
    let category = Category(entity: catEntity!, insertIntoManagedObjectContext: context)
    category.name = categoryField.text // get the name from field and set to category property
    category.color = someColor //assign your required color
    

    Now assign that to your category property in Contact, like this:

    newContact.category = category
    

提交回复
热议问题