Database Reference
In-Depth Information
Next to
Class
, replace
Bowtie
with
Bow_Ties.Bowtie
. This is the fully specified
class name for
Bowtie.swift.
This last step links the runtime
Bowtie
class to the
Bowtie
entity in the data model editor.
Congratulations, you've just made your first managed object subclass in Swift!
Compared with key-value coding, this is a much better way of working with Core
Data entities. There are two main benefits:
1. Managed object subclasses unleash the syntactic power of Swift properties. By
accessing attributes using properties instead of key-value coding, you again
befriend Xcode and the compiler.
2. You gain the ability to override existing methods or to add your own convenience
methods. Note that there are some
NSManagedObject
methods you must never
override. Check Apple's documentation of
NSManagedObject
for a complete list.
To make sure everything is hooked up correctly between the data model and your
new managed object subclass, let's perform a small test.
Open
AppDelegate.swift
and replace
didFinishLaunchingWithOptions
with the
following implementation:
func
application(application:
UIApplication
,
didFinishLaunchingWithOptions
launchOptions: [
NSObject
:
AnyObject
]?) ->
Bool
{
/* Save test bow tie */
let
entity =
NSEntityDescription
.
entityForName
(
"Bowtie"
,
inManagedObjectContext:
managedObjectContext
!)
let
bowtie =
Bowtie
(entity: entity!,
insertIntoManagedObjectContext:
managedObjectContext
)
bowtie.
name
=
"My bow tie"
bowtie.
lastWorn
=
NSDate
()
managedObjectContext
!.
save
(
nil
)
/* Retrieve test bow tie */