Saving CoreData to-many relationships in Swift

匿名 (未验证) 提交于 2019-12-03 02:13:02

问题:

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:

Based on Defining CoreData Relationships in Swift and this, I tried to implement @Keenle's answer for define list objects inside a board:

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

However, I ran into the following error at board.lists.addListObject(lists): 'NSSet' does not have a member named 'addListObject'`

Instead of board.lists.addListObject(lists), I also tried board.lists.listName = listName as implied in this Obj-C example, but that sadly didn't work either.

(Also, The println output is correctly specifying the right board and list.)

Thanks in advance!

回答1:

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.



回答2:

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


回答3:

If you define:

@NSManaged var lists: Set<List> 

Then you can do:

board.lists.insert(list) 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!