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

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 »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »
Explore some of BBCs' most iconic s...
Despite your personal opinion on the BBC at a managerial level, it is undeniable that it has overseen some fantastic British shows in the past, and now thanks to a partnership with Roblox, players will be able to interact with some of these... | Read more »

Price Scanner via MacPrices.net

You can save $300-$480 on a 14-inch M3 Pro/Ma...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer new Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more
Sunday Sale: 13-inch M3 MacBook Air for $999,...
Several Apple retailers have the new 13″ MacBook Air with an M3 CPU in stock and on sale today for only $999 in Midnight. These are the lowest prices currently available for new 13″ M3 MacBook Airs... Read more
Multiple Apple retailers are offering 13-inch...
Several Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices... Read more
Roundup of Verizon’s April Apple iPhone Promo...
Verizon is offering a number of iPhone deals for the month of April. Switch, and open a new of service, and you can qualify for a free iPhone 15 or heavy monthly discounts on other models: – 128GB... Read more

Jobs Board

Relationship Banker - *Apple* Valley Financ...
Relationship Banker - Apple Valley Financial Center APPLE VALLEY, Minnesota **Job Description:** At Bank of America, we are guided by a common purpose to help Read more
IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.