TweetFollow Us on Twitter

The Road to Code: Play it Again, Sam

Volume Number: 25 (2009)
Issue Number: 01
Column Tag: The Road to Code

The Road to Code: Play it Again, Sam

A review of the last year and a half

by Dave Dribin

In Review

Over the last year and a half, we've covered a lot of ground on The Road to Code. We've gone over the basics of programming in C to advanced Cocoa technology, such as Cocoa bindings and Core Data. This month, we're going to put all these concepts together in one article, for those who haven't read each and every article since the beginning of our journey.

Objective-C

There are three legs that support Mac OS X programming, the first being the language. Programs are written for Mac OS X using a language called Objective-C. Objective-C was not created by Apple or even NeXT, but NeXT adopted it in the mid-eighties. Since then, Objective-C has not been used by any other major vendor, thus it's mainly seen as Apple's language.

Objective-C is a strict superset of the cross-platform C language that adds object-oriented programming. C is a statically typed language, meaning every variable is declared as a specific type, like int or float. You still use these primitive types when coding in Objective-C. You also still use C for basic control structures, such as if/then statements, and for and while loops.

Objective-C adds object-oriented programming on top of C's procedural model. Listing 1 shows the interface of a simple Objective-C class to represent a geometric rectangle.

Listing 1: Rectangle class interface

#import <Foundation/Foundation.h>
@interface Rectangle : NSObject
{
   float _leftX;
   float _bottomY;
   float _width;
   float _height;
}
-  (id)initWithLeftX:(float)leftX
            bottomY:(float)bottomY
             rightX:(float)rightX
               topY:(float)topY;
- (float)area;
- (float)perimeter;
@end

The @interface keyword in the first line declares a new class named Rectangle whose superclass is NSObject. Objective-C classes can only have one superclass, meaning multiple inheritance is not supported. The NSObject class is the root of all class hierarchies.

Instance variables are declared between the curly braces. They are listed, one per line, with their type followed by their name, similar to structures in C. Instance variables are only available to the class implementation. They are generally not accessible by other classes.

Instance methods are how others interact with your class and are declared until the @end keyword. Instance methods have a bit of a strange syntax compared to C functions. The return value is in parenthesis and each method argument has a keyword before it. These keywords are actually part of the method name, so the full method name, called a selector, for the first method in the Rectangle class is:

    initWithLeftX:bottomY:rightX:topY:

The arguments are interleaved where the colons are. Calling methods use the square bracket syntax. For example, this is how you would call the area method:

    float area = [rectangle area];

For methods with arguments, the argument values are interleaved with the keyword part of the method. You can also chain multiple method calls together by nesting the square brackets. This is how you would call the constructor to initialize a new Rectangle:

    Rectangle * rectangle =
        [[Rectangle alloc] initWithLeftX:0
                                 bottomY:0
                                  rightX:5
                                    topY:10];

The use of interleaved keywords is unlike most languages, but I think it makes methods much easier to read.

The minus sign in front the method name means it is an instance method: you call this method on an instance of the class. You can use a plus sign to declare a class method:

+ (Rectangle *)zeroRect;

This means you call the method on the class itself:

Rectangle * rectangle = [Rectangle zeroRect];

To define the body of a method, you repeat the method signature and put the body of the method in curly braces:

- (float)area
{
    return _width * _height;
}

This is very much like standard C functions where you use the return keyword to stop executing the method and set the return value. As this example shows, you can directly access instance variables.

Properties

Objective-C 2.0, which was introduced in Mac OS X 10.5, but is also available for the iPhone SDK, has a new feature called properties. Properties simplify the declaring and defining of accessor methods that expose instance variables. Listing 2 is our rectangle interface declared using properties.

Listing 2: Rectangle interface with properties

#import <Foundation/Foundation.h>
@interface Rectangle : NSObject <NSCoding>
{
    float _leftX;
    float _bottomY;
    float _width;
    float _height;
}
@property float leftX;
@property float bottomY;
@property float width;
@property float height;
@property (readonly) float area;
@property (readonly) float perimeter;
- (id)initWithLeftX:(float)leftX
            bottomY:(float)bottomY
             rightX:(float)rightX
               topY:(float)topY;
@end

The @property keyword is used to define a property. Not only does this automatically declare the getter and setter accessor methods, but it also means that they may be accessed using dot notation, instead of method call notation:

    float area = rectangle.area;

You still need to define the body of these implied getter and setter methods, but these may also be generated using the @synthesize keyword:

@synthesize leftX = _leftX;
@synthesize bottomY = _bottomY;
@synthesize width = _width;
@synthesize height = _height;

These lines generate proper accessor methods, tying the properties to a specific instance variable. The property syntax greatly reduces the amount code you have to write for accessors.

Memory Management

All Objective-C objects are allocated on the heap using dynamic memory. It is not possible to allocate an Objective-C object on the stack. Using dynamic memory in C requires using the malloc and free functions. malloc allocates memory from the system and free deallocates memory, returning it to the system.

There are primarily two kinds of memory management bugs you may encounter when dealing with dynamic memory: memory leaks and dangling pointers. Memory leaks occur when you fail to deallocate memory. Over time, your application will use more and more memory, which means less for other applications. Dangling pointers occur when you deallocate memory too soon and active pointers are still pointing to the deallocated memory. Dangling pointers often result in a crash of the application.

In order to avoid memory bugs in C, every malloc must be matched by a free at some point to ensure that all allocated memory is properly returned to the system. To help make this easier, C code usually adopts a system where each piece of dynamic memory has a single owner. The owner is responsible for freeing memory when it is done with it. In order to make this work in practice, you have to setup some conventions so you know who is the owner of a piece of memory.

Traditionally, memory management of objects in Objective-C is handled with a technique called manual reference counting. Reference counting allows multiple owners of an object, compared to the single ownership model of dynamic memory in C. This drastically simplifies the memory management overhead the programmer needs to think about.

To take ownership of an object, you use the retain method to increase the reference count. To relinquish ownership, you use the release method to decrease the reference count. When the reference count reaches zero, the object is deallocated and the memory is returned to the system.

While the ownership rules are simpler in Objective-C than dynamic memory in C, there are still some basic rules that need to be followed in order to ensure proper memory management and avoid memory bugs. Here are the memory management rules as laid out by the Memory Management Programming Guide for Cocoa:

You own any object you create.

If you own an object, you are responsible for relinquishing ownership when you have finished with it.

If you do not own an object, you must not release it.

I suggest reading that entire memory management guide, which you can find on Apple's developer website, as it contains everything you need to know for proper memory management in Objective-C. Some topics of interest are delayed release using autorelease pools, how to write proper accessor methods, and avoiding retain cycles. We also covered these topics in the February 2008 issue.

Garbage Collection

If you are writing applications for Mac OS X 10.4 and earlier or the iPhone, you must use manual reference counting with retain and release. However, if you are fortunate enough to write applications for Mac OS X 10.5 only, you may choose to use garbage collection for memory management.

With garbage collection, you no longer have to worry about using retain and release. The system automatically knows when an object has zero owners and is deallocated. As usual, there are some edge cases you should be aware of, but for all intents and purposes, garbage collection makes your life much easier. I highly recommend it, if you are able to target Mac OS X 10.5.

Libraries

The second leg supporting Mac OS X programming are the system libraries. The libraries define OS X programming as much as the language. Reusable libraries in Objective-C are called frameworks. There are two main system frameworks on Mac OS X: Foundation and AppKit.

Foundation contains much of the lower-level reusable components, such as strings, collections, and file management. These objects are generic and usable in most any application you may be writing, from command line to GUI to server daemons. For example, the root class, NSObject, is part of the Foundation framework. In fact, Foundation is also available when developing for the iPhone. The iPhone's version of Foundation is not quite as full-featured as its Mac OS X counterpart, but you'll find many of the same objects, such as NSString, NSArray, and NSDictionary available on both Mac OS X and iPhone OS.

The AppKit framework is the GUI framework for Mac OS X, providing the system's APIs for GUI components such as windows and buttons. The combination of Foundation and AppKit is known as Cocoa, and Cocoa is really the heart and soul of Mac OS X programming.

Developer Tools

The final leg of support are the developer tools. Apple provides the developer tools for Mac OS X for free. The developer tools include not only a compiler and linker but also a full blown IDE, Xcode, and GUI designer, Interface Builder. Xcode is a fairly advanced IDE. This is where you will spend your time writing code. It allows you to edit, compile, and debug your code all through a nice GUI. It also has features you would expect in a modern IDE, such as autocompletion and some basic refactoring tools.

Interface Builder is an important part of developing for Mac OS X and iPhone. Instead of having to create your user interface in code by instantiating windows and view, then hooking them all up manually, Interface Builder allows you to do this graphically. But it is not a code generating tool, like many GUI designers. Instead of creating code that you have to modify or customize, it creates nib files (which have the .nib or .xib file extension), which contains all the objects for your user interface, freeze dried into a single package. At runtime, your nib file gets loaded, thus creating all your objects and hooking them up appropriately.

Interface Builder not only allows you to layout your user interface, it also allows you to customize their behavior. For example, you can set options on views and controls. One important customization is the autosizing behavior using springs and struts. This defines how controls behave when the window containing the view is resized. It allows views to stretch or stay pinned to a side of the window. An example of the springs and struts settings is shown in the Autosizing section of Figure 1.


Figure 1: Springs and struts

Often you need to write code to customize how GUI components react to user interaction or customize their behavior. Because Interface Builder is not a code generating tool, it uses techniques called actions and outlets to hook up code to the objects defined in the nib file.

Actions are methods that are called in response to a user interacting with a control. For example, buttons call their action method when the button is clicked and menu items call their action method when the menu item is chosen. An action method is a method that has a special return type of IBAction and takes a single argument of type id. Here is an example action method for handling a button press:

- (IBAction)buttonPressed:(id)sender;

The sender argument is typically the control that sent the action, in this case it would be the NSButton that the user clicked. The IBAction return type is an alias for void, so you do not actually return anything. It is used purely as a marker to help Interface Builder identify action methods by scanning the header file.

Outlets allow you to hookup instance variables or properties to objects in the nib. For example, if you wanted to customize the behavior of an NSTableView, you would create an outlet and then use Interface Builder to hookup the outlet to the particular table view in your user interface. To declare an outlet for an instance variable, prefix its type with IBOutlet, as follows:

    IBOutlet NSTableView * _tableView;

To use an outlet object in your code, you must do so after all the outlets in the nib are connected. A special method named awakeFromNib gets called on all objects that were reconstituted from a nib after all objects have been created and all outlet and action connections have been made. It is in awakeFromNib where you would put your code to customize your table view.

MVC

Much of Foundation and AppKit was designed with the model-view-controller design pattern in mind. Design patterns are reusable ideas and architectures used across different programs. The model-view-controller pattern, or MVC pattern, is a common structure for designing GUI applications.

The MVC pattern is shown in Figure 2. Classes in your application should be categorized into three distinct roles: models, views, and controllers. The view classes represent the user interface, and are typically the windows, views, and controls in the AppKit framework. Example view classes include NSButton and NSWindow. The model classes represent the core of your application. For example, if you were writing an address book application, your Person and Address classes would be model classes. This is essentially your application without a user interface. The controller classes glue to together the model and the view by mediating between them.


Figure 2: MVC Architecture

The Rectangle class we've been using as an example is considered a model class. Model classes also know how to convert themselves to and from bytes so they can be stored in a file. The technique of converting an object into a stream of bytes is called archiving, and converting from a stream of bytes is called unarchiving. An object that knows how to archive and unarchive itself must implement the NSCoding protocol. The NSCoding protocol is shown in Listing 3.

Listing 3: NSCoding protocol

@protocol NSCoding
- (void)encodeWithCoder:(NSCoder *)coder;
- (id)initWithCoder:(NSCoder *)decoder;
@end

A protocol is just like a method interface, except it has no implementation. Classes that implement protocols must provide implementations for all methods declared in the protocol interface. To implement NSCoding in our Rectangle class, you could these methods as such:

#pragma mark -
#pragma mark NSCoding
- (void)encodeWithCoder:(NSCoder *)coder
{
    [coder encodeFloat:_leftX forKey:@"leftX"];
    [coder encodeFloat:_bottomY forKey:@"bottomY"];
    [coder encodeFloat:_width forKey:@"width"];
    [coder encodeFloat:_height forKey:@"height"];
}
- (id)initWithCoder:(NSCoder *)decoder
{ 
    self = [super init];
    if (self == nil)
        return nil;
    
    _leftX = [decoder decodeFloatForKey:@"leftX"];
    _bottomY = [decoder decodeFloatForKey:@"bottomY"];
    _width = [decoder decodeFloatForKey:@"width"];
    _height = [decoder decodeFloatForKey:@"height"];
    
    return self;
}

With the Rectangle object implementing we can now convert a rectangle to NSData, a class that represents a collection of bytes, using NSKeyedArchiver:

    Rectangle * rectangle = ...;
    NSData * data =
        [NSKeyedArchiver archivedDataWithRootObject: rectangle];

Conversely, you can convert a previously archived rectangle back into a Rectangle object use NSKeyedUnarchiver:

    NSData * data = ...;
    Rectangle * rectangle =
        [NSKeyedUnarchiver unarchiveObjectWithData: data];

We covered the MVC pattern in detail in the August 2008 issue.

Document-Based Applications

Another design pattern for GUI applications is called a document-based application. A document-based application is one that resolves around the user editing, saving, and opening documents. Because this is such a common kind of application, Cocoa provides classes to help make writing them easier called the document-based architecture. There are three classes that comprise the document-based architecture, but the main one is NSDocument.

When writing a document-based application, you typically subclass NSDocument and customize it for your application. Your subclass not only acts as a controller, mediating between your UI and the model, it also handles saving and opening document files.

Dirty Documents and Undo

Users of document-based applications expect dirty document and undo support. Dirty document support is when the application tracks changes to a document and asks the user to save their changes if the document is closed or the application is quit. This helps ensure that users do not inadvertently lose any changes they made.

Documents use a change count to keep track of dirty state of the document. The change count gets incremented every time the user edits the document. If the change count is zero, the document is clean and may be closed without losing data. If the change count is greater than zero, then the document is dirty. NSDocument does not update the change count for you. If you need to manually increment the change count, you use the updateChangeCount: method of NSDocument:

    [self updateChangeCount:NSChangeDone];

Undo and redo support dovetails with the document change count. Thus, when a user edits a document, the change count should increase and the changes should be undoable. When the user undoes a change, the change count must be decremented, as well. Thus, if the users undoes all the possible edits, the change count is back at zero.

Undo and redo support is handled by the NSUndoManager class. You typically register the previous value with the undo manager before setting the new value. For example, to have the Rectangle class support undo in its setWidth: method you would register the undo action as follows:

- (void)setWidth:(float)width;
{
    if (width == _width)
        return;
    
    NSUndoManager * undoManager = [self undoManager];
    [[undoManager prepareWithInvocationTarget:self] setWidth:_width];
    _width = width;
}

Typically, you do not put undo support into model objects, and you put them in the controller layer. The example included the November 2008 issue showed how to add undo support to our NSDocument subclass. We showed how to use key-value coding (KVC) and key-value observering (KVO) in the document to monitor changes to its rectangles.

Cocoa Bindings

Cocoa bindings is a technology to help reduce the burden of writing controller classes. Much of the controller code is very similar from application to application. It shuttles data from the model to the view and also ensures user interaction from the views is reflected on the model objects.

Because much of the controller code is tedious and repetitive, Apple tried to engineer a technique to make controller code more reusable. The result is Cocoa bindings. By taking advantage of KVC and KVO, Cocoa bindings provides reusable controller objects in the form of NSController subclasses such as NSObjectController and NSArrayController. User interface elements are bound to an NSController instance. These bindings are setup in Interface Builder and rely and key paths. The controllers then use KVC to get the value from model objects and KVO to watch for changes to model objects. Figure 3 is an example from our September 2008 issue that shows how to bind the width of the rectangle to a text field.

Core Data

While writing model objects is not necessarily difficult, there is again a lot of repetitive code. You have to implement NSCoding in the model and undo support in the controller. Again, Apple tries to engineer a technique to make model code more reusable. Apple took a lot of what it learned about object-relational persistence from its WebObjects framework, and re-designed it for use in single user applications. The result is Core Data.

Because of its object-relational mapping lineage, Core Data uses database terms, such as entity and attribute instead of object-oriented terminology like classes and instance variables.

In the December 2008 issue, we transformed our ordinary Rectangle model class to a Core Data entity. Core Data entities are designed using a visual designer and are implemented using NSManagedObject class. You define all the attributes and then Core Data takes care of the rest. Here is our Rectangle class, redesigned as a Core Data entity:


Figure 3: Width binding to a text field


Figure 4: Rectangle entity

We also showed how you subclass NSManagedObject to add in additional derived attributes, such as area and perimeter. Using Core Data to implement your model classes also means you get undo support for free. Any changes made to your model are automatically registered with the undo manager. By handling undo and object persistence support, Core Data saves you from writing a lot of code.

Conclusion

That wraps up a whirlwind summary of what we've learned about programming on Mac OS X. If you haven't already, give it all a try! And check back next month for more adventures on The Road to Code.


Dave Dribin has been writing professional software for over eleven years. After five years programming embedded C in the telecom industry and a brief stint riding the Internet bubble, he decided to venture out on his own. Since 2001, he has been providing independent consulting services, and in 2006, he founded Bit Maki, Inc. Find out more at http://www.bitmaki.com/ and http://www.dribin.org/dave/.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »

Price Scanner via MacPrices.net

Limited-time sale: 13-inch M3 MacBook Airs fo...
Amazon has the base 13″ M3 MacBook Air (8GB/256GB) in stock and on sale for a limited time for $989 shipped. That’s $110 off MSRP, and it’s the lowest price we’ve seen so far for an M3-powered... Read more
13-inch M2 MacBook Airs in stock today at App...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more
Updated Apple MacBook Price Trackers
Our Apple award-winning MacBook Price Trackers are continually updated with the latest information on prices, bundles, and availability for 16″ and 14″ MacBook Pros along with 13″ and 15″ MacBook... Read more
Every model of Apple’s 13-inch M3 MacBook Air...
Best Buy has Apple 13″ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices are the lowest currently available for new 13″ M3 MacBook Airs among... Read more

Jobs Board

Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.