On my Lion app, I have this data model:
The relationship subitem
This issue occurred to me while migrating a project from Objective-C to Swift 2 with XCode 7. That project used to work, and for a good reason: I was using MOGenerator which had replacement methods to fix this bug. But not all methods require a replacement.
So here's the complete solution with an example class, relying on default accessors as much as possible.
Let's say we have a List with ordered Items
First a quick win if you have a one/to-many relationship, the easiest is to just do:
item.list = list
instead of
list.addItemsObject(item)
Now, if that's not an option, here's what you can do:
// Extension created from your DataModel by selecting it and
// clicking on "Editor > Create NSManagedObject subclass…"
extension List {
@NSManaged var items: NSOrderedSet?
}
class List
// Those two methods work out of the box for free, relying on
// Core Data's KVC accessors, you just have to declare them
// See release note 17583057 https://developer.apple.com/library/prerelease/tvos/releasenotes/DeveloperTools/RN-Xcode/Chapters/xc7_release_notes.html
@NSManaged func removeItemsObject(item: Item)
@NSManaged func removeItems(items: NSOrderedSet)
// The following two methods usually work too, but not for NSOrderedSet
// @NSManaged func addItemsObject(item: Item)
// @NSManaged func addItems(items: NSOrderedSet)
// So we'll replace them with theses
// A mutable computed property
var itemsSet: NSMutableOrderedSet {
willAccessValueForKey("items")
let result = mutableOrderedSetValueForKey("items")
didAccessValueForKey("items")
return result
}
func addItemsObject(value: Item) {
itemsSet.addObject(value)
}
func addItems(value: NSOrderedSet) {
itemsSet.unionOrderedSet(value)
}
end
Of course, if you're using Objective-C, you can do the exact same thing since this is where I got the idea in the first place :)