Saving CoreData to-many relationships in Swift

2019-01-13 11:04发布

问题:

I have a one-to-many relationship that looks like so,

I've set up my model classes in a file to match:

import CoreData
import Foundation

class Board: NSManagedObject {
    @NSManaged var boardColor: String
    @NSManaged var boardCustomBackground: AnyObject?
    @NSManaged var boardID: String
    @NSManaged var boardName: String
    @NSManaged var lists: NSSet
}

class List: NSManagedObject {
    @NSManaged var listID: String
    @NSManaged var listName: String
    @NSManaged var board: Board
}

Because I'm fetching data from multiple JSON endpoints, I have to save my lists seperately from my boards. What I want to do is create/update a list for a board with a matching boardID.

Here's where I am after multiple attempts:

func saveList(boardID: String, listName: String, listID: String) {
    let request = NSFetchRequest(entityName: "Board")
    var error: NSError? = nil
    request.predicate = NSPredicate(format: "boardID like %@", boardID)
    let results: NSArray = context.executeFetchRequest(request, error: &error)
    if results.count > 0 {
        for result in results {
            let board = result as Board
            let list = NSEntityDescription.insertNewObjectForEntityForName("List", inManagedObjectContext: context) as List
            println("