Database Reference
In-Depth Information
Adding managed object subclasses
In the previous chapter you learned how to create custom managed object
subclasses for your Core Data entities. It's more convenient to work this way, so
this is what you'll do for Dog and Walk as well.
Go to Editor\Create NSManagedObject Subclass… and choose the Dog Walk
model and then both the Dog and Walk entities. Make sure you choose Swift as
the language and click Create .
Dog.swift should look like this:
import Foundation
import CoreData
class Dog: NSManagedObject {
@NSManaged var name: String
@NSManaged var walks: NSOrderedSet
}
Like before, the name attribute is a String . But what about the walks relationship?
Core Data represents to-many relationships using sets, not arrays. Because you
made the walks relationship ordered, you've got an ordered set.
Note: NSSet seems like an odd choice, doesn't it? Unlike arrays, sets don't
allow accessing their members by index. In fact, there's no ordering at all!
Core Data uses NSSet because a set forces uniqueness in its members. The
same object can't feature more than once in a to-many relationship.
If you need to access individual objects by index, you can check the Ordered
checkbox in the visual editor, as you've done here. Core Data will then
represent the relationship as an NSOrderedSet .
Walk.swift should look like this:
import Foundation
import CoreData
class Walk: NSManagedObject {
@NSManaged var date: NSDate
@NSManaged var dog: Dog
}
The inverse relationship back to Dog is simply a variable of type Dog . Easy as pie.
 
Search WWH ::




Custom Search