Chapter 10: Accessors

Accessors are the methods used to set and examine the instance variables of a class. The standard naming convention in Cocoa is to use the name of the variable as the getter (or accessor) and the variable name prefixed with “set” as the setter (or mutator). That’s the way Aaron Hillegass does things in his book, so I’m sure that’s something most Cocoa developers are used to.

The other way of accessing instance variables is Key-Value Coding, or KVC for short. You don’t need KVC if you’re only interfacing with your own code. However, bindings and Core Data require KVC, so you’ll want to be sure to learn KVC to take advantage of these technologies.

I did find a few surprises in the chapter. One was that apparently Key-Value Coding may work even if the class doesn’t have properly named setters and getters. If the regular ones aren’t available, KVC will try accessors prefixed with an underscore, or even try addressing them directly (I presume this is something like object.var). I can’t think of any good reason to not create accessors with the proper names, so this is an exception I don’t think I need to pay much attention to.

The second new thing was accessors using the prefix get, something like -(void)getValue:(void *)aBuffer. This returns the value by reference, which isn’t that common in developer-written code. Cocoa does use it in a few spots, such as NSColor’s - (void)getRed:(CGFloat *)redVal green:(CGFloat *)greenVal blue:(CGFloat *)blueVal alpha:(CGFloat *)alphaVal. It has to work this way, because a method can only return a single float without using return-by-reference.

It’s hard to think of a worthwhile example to code for this, since accessors are such a fundamental part of any classes that have instance variables, so I’ll move on without an example program.

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s