iosswiftcore-datansorderedset

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


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?


Solution

  • 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