Saving CoreData to-many relationships in Swift

2019-01-13 11:15发布

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

coredata model

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("                

3条回答
戒情不戒烟
2楼-- · 2019-01-13 11:31

If you define:

@NSManaged var lists: Set<List>

Then you can do:

board.lists.insert(list)
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-13 11:35

In a one-to-many relationship, it is easier to set the "to-one" direction of the inverse relationships, in your case just

list.board = board

so that the extension methods are actually not needed here.

查看更多
ゆ 、 Hurt°
4楼-- · 2019-01-13 11:58

You should invoke addListObject(...) on board object:

board.addListObject(list) // notice that we pass just one object

Additionaly, if you want to be able to add a set of lists to particular board object, you can enhance you Board class extension with methods that accept set of objects:

func addList(values: NSSet) {
    var items = self.mutableSetValueForKey("lists");
    for value in values {
        items.addObject(value)
    }
}

func removeList(values: NSSet) {
    var items = self.mutableSetValueForKey("lists");
    for value in values {
        items.removeObject(value)
    }
}
查看更多
登录 后发表回答