在Swift中保存Core Data to-many关系

时间:2014-08-04 20:34:52

标签: ios macos core-data swift relationship

我有一对多的关系,看起来像这样,

coredata model

我已将模型类设置在一个文件中以匹配:

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
}

因为我从多个JSON端点获取数据,所以我必须单独从我的板上保存我的列表。 我想要做的是为具有匹配的boardID 的电路板创建/更新列表。

这是我多次尝试后的位置:

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(" want to save \(listName) in \(board.boardName)")
            board.lists.addListObject(lists)
            list.listName = listName
            list.listID = listID
        }
    }
}

基于Defining CoreData Relationships in Swiftthis,我试图实现@Kenenle对板内定义列表对象的回答:

import Foundation

extension Board {
    func addListObject(value:List) {
        var items = self.mutableSetValueForKey("lists");
        items.addObject(value)
    }

    func removeListObject(value:List) {
        var items = self.mutableSetValueForKey("lists");
        items.removeObject(value)
    }
}

但是,我在board.lists.addListObject(lists)处遇到以下错误: 'NSSet'没有名为'addListObject'的成员

而不是board.lists.addListObject(lists),我也尝试了board.lists.listName = listName Obj-C example所暗示的,但遗憾的是,这也不起作用。

(另外,println输出正确指定了正确的电路板和列表。)

提前致谢!

3 个答案:

答案 0 :(得分:30)

在一对多关系中,设置“一对一”方向更容易 反向关系,在你的情况下只是

list.board = board

这样实际上不需要扩展方法。

答案 1 :(得分:6)

您应该在addListObject(...)对象上调用board

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

另外,如果您希望能够向特定board对象添加一组列表,则可以使用接受一组对象的方法增强Board类扩展:

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)
    }
}

答案 2 :(得分:3)

如果你定义:

@NSManaged var lists: Set<List>

然后你可以这样做:

board.lists.insert(list)