There are a couple of ways to create or generate NSManagedObject subclasses. In the simplest of setups, an NSManagedObject subclass contains just the properties for a certain managed object and nothing else. If this is the case, then you can let Xcode generate your model classes for you.
This is actually what Xcode does by default. Build your project and try to write some code, such as the following:
let fam = FamilyMember(entity: FamilyMember.entity(),
insertInto: managedObjectContext)
It will work automatically; you don't have to write any code yourself. Don't worry about what the preceding code does just yet, we'll get into that very soon. The point is that you can see that a FamilyMember class exists in your project even though you didn't have to create one yourself.
If this default doesn't suit the approach you want to example, if you want to prevent your code from modifying your models by defining your variables as private(set),) you may want to create a custom subclass instead of allowing Xcode to generate one for you. A custom NSManagedObject subclass for FamilyMember would look like this:
class FamilyMember: NSManagedObject {
@NSManaged private(set) var name: String
@NSManaged private(set) varfavoriteMovies: [Movie]?
}
This custom FamilyMember subclass makes sure that external code can't modify our instances. Depending on your application, it might be a good idea to implement this since it will ensure that your models can't accidentally change.
One final option you have is to let Xcode generate the properties for your NSManagedObject as an extension on a class you will define. This is particularly useful if you have some custom-stored properties that you'd like to define on your model or if you have a customized NSManagedObject subclass that you can use as the base for all of your models.
For our FamilyMovies app, we'll have Xcode generating the model definition classes since we don't have any custom properties that we'd like to add. In the model editor, select each entity and make sure that the Codegen field is set to Class Definition; you can find this field in the Data Model inspector panel:
