Database Reference
In-Depth Information
Even though you can do everything directly on
NSManagedObject
using key-value
coding, that doesn't mean you should!
The biggest problem with key-value coding is the fact that you're accessing of data
using strings instead of strongly-typed classes. This is often jokingly referred to as
writing
stringly typed
code. :]
As you probably know from experience, “stringly typed” code is vulnerable to silly
human errors such as mistyping and misspelling. Key-value coding also doesn't
take full advantage of Swift's type-checking and Xcode's auto-completion.
The best alternative to key-value coding is to create
NSManagedObject
subclasses for
each entity in your data model. That means there will be a
Bowtie
class with correct
types for each property!
Xcode can automatically generate the subclass for you. Make sure you still have
Bow_Ties.xcdatamodeld
open, and go to
Editor\Create NSManagedObject
Subclass…
. Select the data model and then the
Bowtie
entity in the next two
dialog boxes, then select
Swift
as the language option in the final box. If you're
asked, say
No
to creating an Objective-C bridging header. Click
Create
to save the
file.
Go to
Bowtie.swift
.
It should look like this:
import
Foundation
import
CoreData
class
Bowtie:
NSManagedObject
{
@NSManaged
var
name:
String
@NSManaged
var
isFavorite:
NSNumber
@NSManaged
var
lastWorn:
NSDate
@NSManaged
var
rating:
NSNumber
@NSManaged
var
searchKey:
String
@NSManaged
var
timesWorn:
NSNumber
@NSManaged
var
photoData:
NSData
@NSManaged
var
tintColor:
AnyObject
}