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

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 »
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 »

Price Scanner via MacPrices.net

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
Sunday Sale: Apple iPad Magic Keyboards for 1...
Walmart has Apple Magic Keyboards for 12.9″ iPad Pros, in Black, on sale for $150 off MSRP on their online store. Sale price for online orders only, in-store price may vary. Order online and choose... Read more
Apple Watch Ultra 2 now available at Apple fo...
Apple has, for the first time, begun offering Certified Refurbished Apple Watch Ultra 2 models in their online store for $679, or $120 off MSRP. Each Watch includes Apple’s standard one-year warranty... Read more
AT&T has the iPhone 14 on sale for only $...
AT&T has the 128GB Apple iPhone 14 available for only $5.99 per month for new and existing customers when you activate unlimited service and use AT&T’s 36 month installment plan. The fine... Read more
Amazon is offering a $100 discount on every M...
Amazon is offering a $100 instant discount on each configuration of Apple’s new 13″ M3 MacBook Air, in Midnight, this weekend. These are the lowest prices currently available for new 13″ M3 MacBook... Read more
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

Jobs Board

*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
IT Systems Engineer ( *Apple* Platforms) - S...
IT Systems Engineer ( Apple Platforms) at SpaceX Hawthorne, CA SpaceX was founded under the belief that a future where humanity is out exploring the stars is Read more
Nurse Anesthetist - *Apple* Hill Surgery Ce...
Nurse Anesthetist - Apple Hill Surgery Center Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
Housekeeper, *Apple* Valley Village - Cassi...
Apple Valley Village Health Care Center, a senior care campus, is hiring a Part-Time Housekeeper to join our team! We will train you for this position! In this role, Read more
Sublease Associate Optometrist- *Apple* Val...
Sublease Associate Optometrist- Apple Valley, CA- Target Optical Date: Apr 20, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92307 **Requisition Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.