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

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

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.