Digging in to Objective-C, Part 2
Volume Number: 19 (2003)
Issue Number: 3
Column Tag: Getting Started
Digging in to Objective-C, Part 2
by Dave Mark
In this month's column, we're going to dig through last month's Objective-C source code. Before we do that, I'd like to take a little detour and share a cool Mac OS X experience I had this weekend.
FTP From the Finder
The more time I spend in Mac OS X, the more I love it. There are so many nooks and crannies to explore. I've installed PHP and mySQL servers on my machine and fiddled with the default Apache installation as well. I've re-honed my rusty Unix skills, spending untold amounts of time in the Terminal app. Before there were any native FTP apps in OS X, I had to do all my FTPing using the Terminal. Finally, apps like Interarchy, Fetch, and the like made the move to OS X and I got used to those drag and drop interfaces. Then I ran into a problem which turned into a really cool discovery.
I own a licensed copy of Interarchy. When they introduced a beta version of their latest and greatest FTP client, someone from Stairways sent out a call for beta-testers. To make a long story short, I deleted the original, did all my FTPing using the beta client. No problem. Except that one day, I came into the office to discover that the beta had expired and I needed an FTP client to retrieve the previous version from the company's site.
So I found myself needing an alternative FTP client. On a whim, I decided to experiment with Safari before turning back to the primitive Unix FTP client. In Safari's address field, I typed in this URL:
ftp.interarchy.com
I hit the return, the screen flashed a bit, but nothing seemed to happen. It was as if Safari ignored my request. But then, out of the corner of my eye, I noticed a new icon on my desktop (see Figure 1.) Very cool! In effect, the FTP site had been mounted as a volume on my desktop. When I opened a new file browser, I was able to navigate through the site, just as I would my hard drive. I used the Finder to copy the new FTP client onto my hard drive.
Figure 1. The ftp.interarchy.com icon on my desktop
Somewhere in the back of my brain, I remembered that I could use the Finder to connect to an AppleShare server. Wonder if that would work with an FTP server as well. Hmmm. I selected Connect to Server... from the Finder's Go menu (Figure 2). When the dialog appeared, I typed in fto.interarchy.com. The Finder reported an error connecting to afp://ftp.interarchy.com.
Figure 2. Using the Finder to connect to an FTP server.
Interesting. Either the Finder uses the AppleShare protocol as its default or I somehow (by accessing an AppleShare server, perhaps) set AppleShare as my default protocol. Hmmm. So I gave this a try:
ftp://ftp.interarchy.com
Guess what? It worked!!! I experimented with some other ftp servers and they all worked the same way. Cool! I love Mac OS X.
To be fair, the Finder doesn't do all the nifty tricks that Interarchy does. For example, the mounted disk is read-only, so you couldn't use this trick to manage your web site. I asked around, and the folks who really know about this stuff all said the same thing. An amazing bit of coding to add this feature to the OS. Nicely done, Apple.
Walking Through the Employee Code
OK, let's get back to the code. Last month, I introduced two versions of the same program, one in C++ and one in Objective-C. The goal was for you to see the similarities between the two languages and to get a handle on some of the basics of Objective-C. If you don't have a copy of last month's MacTech, download the source from mactech.com and take a quick read-through of the C++ code. Our walk-through will focus on the Objective-C code.
In general, MacTech source code is stored in:
ftp://ftp.mactech.com/src/
Once you make your way over there, you'll see a bunch of directories, one corresponding to each issue. This year's issues all start with 19 (the 19th year of publication). 19.02 corresponds to the February issue. You'll want to download cpp_employee.sit and objc_employee.sit. The former is the C++ version and the latter the Objective-C version.
For convenience, there's a web page that points to this at:
http://www.mactech.com/editorial/filearchives.html
Employee.h
Employee.h starts off by importing Foundation.h, which contains the definitions we'll need to work with the few elements of the Foundation framework we'll take advantage of.
#import <Foundation/Foundation.h>
The #import directive replaces the #ifdef trick most of us use to avoid cyclical #includes. For example, suppose you have two classes, each of which reference the other. So ClassA.h #includes ClassB.h and ClassB.h #includes ClassA.h. Without some kind of protection, the #includes would form an infinite #include loop.
A typical C++ solution puts code like this in the header:
#ifndef _H_Foo
#define _H_Foo
#pragma once // if your compiler supports it
// put all your header stuff here
#endif // _H_Foo
This ensures that the header file is included only once. In Objective-C, this cleverness is not necessary. Just use #import for all your #includes and no worries.
A Mr. Richard Feder of Ft. Lee, New Jersey writes, "How come we need the Foundation.h include file? Where does Objective-C stop and Foundation begin?" Good question!
As I never get tired of saying, I am a purist when it comes to learning programming languages. Learn C, then learn Objective-C. Learn Objective-C, then learn Cocoa and the Foundation framework. In general, I'll try to keep the Foundation elements out of my Objective-C code. When I do include some Foundation code, I'll do my best to mark it clearly so you understand what is part of the Objective-C language and what is not.
If you refer back to the C++ version of Employee.h, you'll see that our Employee class declaration includes both data members and member functions within its curly braces. In Objective-C, the syntax is a little different. For starters, the class is declared using an @interface statement that follows this format:
@interface Employee : NSObject {
@private
char employeeName[20];
long employeeID;
float employeeSalary;
}
- (id)initWithName:(char *)name andID:(long)id
andSalary:(float)salary;
- (void)PrintEmployee;
- (void)dealloc;
@end
Note that the data members, known to Objective-C as fields, are inside the curly braces, while the member functions (methods) follow the close curly brace. The whole shebang ends with @end.
Note that we derived our class from the NSObjecct class. Any time you see the letters NS at the start of a class, object, or method name, think Foundation Framework. NS stands for NextStep and is used throughout the Foundation classes. To keep things pure, I could have declared Employee as an Object subclass or as a root class, but since most of the code you write will inherit from some Cocoa class, I figure let's go with this minimal usage. When you derive from NSObject, you inherit a number of methods and fields. We'll get to know NSObject in detail in future columns.
Notice the use of the @private access modifier. Like C++, Objective-C offers 3 modifiers, @private, @protected, and @public. The default is @protected.
Objective-C method declarations start with either a "-" or a "+". The "-" indicates an instance method, a method tied to an instance of that class. The "+" indicates a class method, a method tied to the entire class. We'll get into class methods in a future column.
Objective-C Parameters
Perhaps the strangest feature of Objective-C is the way parameters are declared. The best way to explain this is by example. Here's a method with no parameters:
- (void)dealloc;
Pretty straightforward. The function is named "dealloc", it has no parameters, and it does not return a value.
- (void)setHeight:(int)h;
This function is named "height:". It does not return a value but does take a single parameter, an int with the name h. The ":" is used to separate parameters from other parameters and from the function name.
A word on naming your accessor functions: Though this is not mandatory, most folks name their getter functions to match the name of the field being retrieved, then put the word "set" in front of that to name the setter function.
As an example, consider these two functions:
- (int)height; // Returns the value of the height field
- (void)setHeight:(int)h; // Sets the height field to the value in h
As I said, this naming convention is not mandatory, but it is widely used. There is a book out there that tells you to use the same exact name for your setter and getter (both would be named height in the example above), but everyone I've discussed this with poo-poos this approach in favor of the standard we just discussed. In addition, as you make your way through the Developer doc on your hard drive, you'll see the accessor naming convention described above used throughout.
The last important change here is when you have more than one parameter. You add a space before each ":(type)name" series. For example:
- (id)initWithName:(char *)name andID:(long)id
andSalary:(float)salary;
This function is named "initWithName:andID:andSalary:", returns the type "id", and takes 3 parameters (a (char *), a long, and a float). This is a bit tricky, but you'll get used to it.
The type "id" is Objective-C's generic object pointer type. We'll learn more about it in future columns.
Employee.m
Employee.m starts off by importing the Employee.h header file.
#import "Employee.h"
The rest off the file makes up the implementation of the Employee class. The implementation compares to the C++ concept of definition. It's where the actual code lives. The first function is initWithName:andID:andSalary:. The function takes three parameters and initializes the fields of the Employee object, then prints a message to the console using printf. Note that the function returns self, a field inherited from NSObject, which is a pointer to itself.
@implementation Employee
- (id)initWithName:(char *)name andID:(long)id
andSalary:(float)salary {
strcpy( employeeName, name );
employeeID = id;
employeeSalary = salary;
printf( "Creating employee #%ld\n", employeeID );
return self;
}
PrintEmployee uses printf to print info about the Employee fields to the console.
- (void)PrintEmployee {
printf( "----\n" );
printf( "Name: %s\n", employeeName );
printf( "ID: %ld\n", employeeID );
printf( "Salary: %5.2f\n", employeeSalary );
printf( "----\n" );
}
dealloc is an NSObject method that we are overriding simply so we can print our "Deleting employee" message. The line after the printf is huge. For starters, it introduces the concept of "sending a message to a receiver". This is mildly analogous to the C++ concept of dereferencing an object pointer to call one of its methods. For now, think of the square brackets as surrounding a receiver (on the left) and a message (on the right). In this case, we are sending the dealloc message to the object pointed to by super.
As it turns out, "super" is another field inherited from NSObject. It points to the next object up in the hierarchy, the NSObject the Employee was subclassed from. Basically, the super we are sending the message to is the object we overrode to get our version of dealloc called. By overriding super's dealloc, we've prevented it from being called. By sending it the dealloc method ourselves, we've set things right.
- (void)dealloc {
printf( "Deleting employee #%ld\n", employeeID );
[super dealloc];
}
@end
main.m
Finally, here's main.m. We start off by importing Foundation.h and Employee.h. Notice that Employee.h already imports Foundation.h. That's the beauty of #import. It keeps us from including the same file twice.
#import <Foundation/Foundation.h>
#import "Employee.h"
The function main starts off like its C counterpart, with the parameters argc and argv that you've known since childhood.
int main (int argc, const char * argv[]) {
NSAutoreleasePool is a memory management object from the Foundation Framework. We're basically declaring an object named pool that will serve memory to the other Foundation objects that need it. We will discuss the ins and outs of memory management in a future column. For the moment, notice that we first send an alloc message to NSAutoreleasePool, and then send an init message to the object returned by alloc. The key here is that you can nest messages. The alloc message creates the object, the init message initializes the object. This combo is pretty typical.
NSAutoreleasePool * pool =
[[NSAutoreleasePool alloc] init];
Now we create our two employees. Instead of alloc and init, we're going to alloc and initWithName:andID:andSalary: which suits our needs much better than the inherited init would. Still nested though. Note that we are taking advantage of the self returned by initWithName:andID:andSalary:. That's the object pointer whose type is id. Think about the compiler issues here. The compiler did not complain that you were assigning an id to an Employee pointer. This is important and will come up again in other programs we create.
Employee* employee1 = [[Employee alloc] initWithName:"Frank Zappa" andID:1
andSalary:200];
Employee* employee2 = [[Employee alloc] initWithName:"Donald Fagen" andID:2 andSalary:300];
Once our objects are created, let's let them do something useful. We'll send them each a PrintEmployee message.
[employee1 PrintEmployee];
[employee2 PrintEmployee];
Next, we'll send them each a release message. This tells the NSAutoreleasePool that we have no more need of these objects and their memory can be released. Finally, we release the memory pool itself.
[employee1 release];
[employee2 release];
[pool release];
return 0;
}
Till Next Month...
The goal of this program was not to give you a detailed understanding of Objective-C, but more to give you a sense of the basics. Hopefully, you have a sense of the structure of a class interface and implementation, function declarations, parameter syntax, and the basics of sending messages to receivers.
One concept we paid short shrift to was memory management. I realize we did a bit of hand-waving, rather than dig into the details of NSAutoreleasePool and the like, but I really want to make that a column unto itself.
Before I go, I want to say a quick thanks to Dan Wood and John Daub for their help in dissecting some of this stuff. If you see these guys at a conference, please take a moment to say thanks and maybe treat them to a beverage of choice.
And if you experts out there have suggestions on improvements I might make to my code, I am all ears. Please don't hesitate to drop an email to feedback@mactech.com.
See you next month!
Dave Mark is a long-time Mac developer and author and has written a number of books on Macintosh development, including Learn C on the Macintosh, Learn C++ on the Macintosh, and The Macintosh Programming Primer series. Be sure to check out Dave's web site at http://www.spiderworks.com, where you'll find pictures from Dave's visit to MacWorld Expo in San Francisco (yes, there are a bunch of pictures of Woz on there!)