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

Seven Knights Idle Adventure drafts in a...
Seven Knights Idle Adventure is opening up more stages, passing the 15k mark, and players may find themselves in need of more help to clear these higher stages. Well, the cavalry has arrived with the introduction of the Legendary Hero Iris, as... | Read more »
AFK Arena celebrates five years of 100 m...
Lilith Games is quite the behemoth when it comes to mobile games, with Rise of Kingdom and Dislyte firmly planting them as a bit name. Also up there is AFK Arena, which is celebrating a double whammy of its 5th anniversary, as well as blazing past... | Read more »
Fallout Shelter pulls in ten times its u...
When the Fallout TV series was announced I, like I assume many others, assumed it was going to be an utter pile of garbage. Well, as we now know that couldn't be further from the truth. It was a smash hit, and this success has of course given the... | Read more »
Recruit two powerful-sounding students t...
I am a fan of anime, and I hear about a lot that comes through, but one that escaped my attention until now is A Certain Scientific Railgun T, and that name is very enticing. If it's new to you too, then players of Blue Archive can get a hands-on... | Read more »
Top Hat Studios unveils a new gameplay t...
There are a lot of big games coming that you might be excited about, but one of those I am most interested in is Athenian Rhapsody because it looks delightfully silly. The developers behind this project, the rather fancy-sounding Top Hat Studios,... | Read more »
Bound through time on the hunt for sneak...
Have you ever sat down and wondered what would happen if Dr Who and Sherlock Holmes went on an adventure? Well, besides probably being the best mash-up of English fiction, you'd get the Hidden Through Time series, and now Rogueside has announced... | Read more »
The secrets of Penacony might soon come...
Version 2.2 of Honkai: Star Rail is on the horizon and brings the culmination of the Penacony adventure after quite the escalation in the latest story quests. To help you through this new expansion is the introduction of two powerful new... | Read more »
The Legend of Heroes: Trails of Cold Ste...
I adore game series that have connecting lore and stories, which of course means the Legend of Heroes is very dear to me, Trails lore has been building for two decades. Excitedly, the next stage is upon us as Userjoy has announced the upcoming... | Read more »
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 »

Price Scanner via MacPrices.net

Apple introduces the new M4-powered 11-inch a...
Today, Apple revealed the new 2024 M4 iPad Pro series, boasting a surprisingly thin and light design that pushes the boundaries of portability and performance. Offered in silver and space black... Read more
Apple introduces the new 2024 11-inch and 13-...
Apple has unveiled the revamped 11-inch and brand-new 13-inch iPad Air models, upgraded with the M2 chip. Marking the first time it’s offered in two sizes, the 11-inch iPad Air retains its super-... Read more
Apple discontinues 9th-gen iPad, drops prices...
With today’s introduction of the new 2024 iPad Airs and iPad Pros, Apple has (finally) discontinued the older 9th-generation iPad with a home button. In response, they also dropped prices on 10th-... Read more
Apple AirPods on sale for record-low prices t...
Best Buy has Apple AirPods on sale for record-low prices today starting at only $79. Buy online and choose free shipping or free local store pickup (if available). Sale price for online orders only,... Read more
13-inch M3 MacBook Airs on sale for $100 off...
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, along with Amazon’s, are the lowest currently available for new 13″... Read more
Amazon is offering a $100 discount on every 1...
Amazon has every configuration and color of Apple’s 13″ M3 MacBook Air on sale for $100 off MSRP, now starting at $999 shipped. Shipping is free: – 13″ MacBook Air (8GB RAM/256GB SSD): $999 $100 off... Read more
Sunday Sale: Take $150 off every 15-inch M3 M...
Amazon is now offering a $150 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1149 for models with 8GB of RAM and 256GB of storage: – 15″ M3 MacBook... Read more
Apple’s 24-inch M3 iMacs are on sale for $150...
Amazon is offering a $150 discount on Apple’s new M3-powered 24″ iMacs. Prices start at $1149 for models with 8GB of RAM and 256GB of storage: – 24″ M3 iMac/8-core GPU/8GB/256GB: $1149.99, $150 off... Read more
Verizon has Apple AirPods on sale this weeken...
Verizon has Apple AirPods on sale for up to 31% off MSRP on their online store this weekend. Their prices are the lowest price available for AirPods from any Apple retailer. Verizon service is not... Read more
Apple has 15-inch M2 MacBook Airs available s...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs available starting at $1019 and ranging up to $300 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at Apple.... Read more

Jobs Board

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
*Apple* App Developer - Datrose (United Stat...
…year experiencein programming and have computer knowledge with SWIFT. Job Responsibilites: Apple App Developer is expected to support essential tasks for the RxASL 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.