TweetFollow Us on Twitter

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!)

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom 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.