Database Reference
In-Depth Information
from a static or local variable.) In addition, if the target object has neither an
accessor nor an
ivar
, the target object will still have a chance to respond to
the request before an error occurs via the
-valueForUndefinedKey:
method. Lastly,
all the properties of an
NSManagedObject
are queryable via the KVC protocol.
What this means is if we have an
NSManagedObject
defined in our model, we can
retrieve an instance of that object and access its properties without having
to implement a
single line of code
in the target object!
-setValue:forKey:
Dynamically accessing properties on an object is a useful skill, but it's only
half of what KVC does. The other half is the ability to dynamically set
attributes on an object in much the same manner that we can retrieve them.
Normally, we would change the
name
attribute on an
Recipe
object by calling
the setter method.
Recipe *myRecipe = ...
[myRecipe setName:@
"Yummy Cookies"
];
As in the earlier getter accessor, preexisting knowledge of the
Recipe
object is
required in order to use that accessor without compiler warnings. However,
with KVC, we can access it in a more dynamic manner.
id myRecipe = ...
[myRecipe setValue:@
"Yummy Cookies"
forKey:@
"name"
];
This call attempts to use the setter
-setName:
if it is available; if it is not, the
call will look for and use the attribute directly if it is available, and failing
that, it will call
-setValue:forUndefinedKey:
on the target object. The combination
of the dynamic getter coupled with the dynamic setter allows us to manipulate
objects without having to write accessors and without having to know (or
care!) if they exist. This is used to great effect in one of the Core Data recipes
to create a preferences singleton object that reads its values from a properties
table. See
Chapter 10,
Dynamic Parameters
, on page 179
.
@property
In addition, as of OS X 10.5 Leopard, we have the keyword
@property
, which
allows us to synthesize accessors to attributes on an object. This feature plays
very nicely with KVC, and the two can be used together to produce extremely
dynamic and flexible code. By utilizing the
@property
keyword, we can instruct
the compiler to generate getter and setter accessors that are KVO-compliant.
In a 32-bit application, we can define the
@property
that has the same object
type and name as a defined ivar. This will tell the compiler that getter and
setter accessors exist or will exist for that ivar. In a 64-bit application, the