Swift 2.0 one-to-many relationship - still NSOrderedSet?

2.6k Views Asked by At

In Swift 2.0, are one-to-many relationships in Core Data still NSOrderedSets?

I cannot seem to be able to cast/downcast appropriately to ever not throw errors.

Does anyone have a simple example of this in Swift 2.0?

2

There are 2 best solutions below

1
On BEST ANSWER

Unfortunately CoreData with swift is still a huge pain especially with ordered one-many relationships. Yes, it is still NSOrderedSet that is being used by CoreData for to-many relationships. The question is how to add/remove items to this. Xcode has never been able to generate accessors properly for the ordered set so far - even in Objective let alone Swift!!.

There is this thread on saving to-many relations in Swift: How to define CoreData relationship in Swift?

But, alas!, nothing mentioned in this thread ever works in Swift 2.0 world. So what is the workaround for now? I digged into this, and the only way to get this working is generating the sources for entities in question, in Objective C, and not in swift and exporting the headers of them in the bridging header. Also you need to ensure you include an important workaround fix for Xcode to generate proper accessors for ordered set:

https://github.com/CFKevinRef/KCOrderedAccessorFix

You should ensure to call- model.kc_generateOrderedSetAccessors() in your model creation code in AppDelegate to invoke this fix.

Once done, you can now safely start using the generated accessors on your model to add items to a to-many relationship.

I have created a sample project and is in github and hope it helps-

https://github.com/shripada/CoreDataToManyRelationshipInSwift2.0

2
On

Only if you flag the relationship with the option "Ordered". If not, then it's a NSSet.

I don't agree with the accepted answer because in Swift 2.0 bridging from NSSet to a Set happens automatically, so if you can subclass the CoreData entity, you can just write:

@NSManaged var oneToManyOfTypeFoo: Set<Foo>

And then adding and removing elements becomes trivial, because you can just use the insert and remove methods from Set.