TweetFollow Us on Twitter

May 97 Getting Started

Volume Number: 13 (1997)
Issue Number: 5
Column Tag: Getting Started

More Objective-C

by Dave Mark, ©1997, All Rights Reserved. http://www.spiderworks.com

Last month, we took our first taste of Objective-C. We learned that Objective-C sources use the extension ".m" for main source files and ".h" for header files. The type "id" is used to declare a generic pointer which allows us to delay type binding decisions. We learned that most objects are derived from the Root class Object. The Object class features variables and methods inherited by all other classes. One of these variables is "isa" which specifies the class to which an object belongs.

We saw the form for a class interface:

 MySuperClass
{
 instance variable declarations
}
method declarations

We also learned about Objective-C's funky form of method declaration:

- (int)getX:(int)x andY:(int)y;

Where the leading minus sign marks the function as an instance method - as opposed to a "+", which marks a method as a class method, like a C++ static method. The first "int" is the return type, and the other "int"s are the parameter types. The name of the method above is "getX:andY:" The default type is id, so if you leave out any of the types (including the return type) the type is set to id.

We also learned about the #import compiler directive, used to avoid multiple inclusion of a .h file:

#import "Object.h"

Alternatively, you can avoid all the extra junk you get when you import a classes' header file by using the @class directive to let the compiler know that a reference is to a legal class:


Finally, we saw the form used for the actual implementation of a class:

#import "MyClass.h"

Message Receivers and Message Syntax

Now it's on to new material. Once you declare your class and use that declaration to define an object, it's time to bring that object to life by sending it a message. In C++, you call an object's member function using the object itself to make the call:

myObjectPtr->MemberFunction();

In Objective-C, a message is said to be sent to a receiver using the following syntax:

[receiver message];

The receiver is an object and the message is a method, along with its associated parameters. The message is sent (and the appropriate method selected) at runtime. For example, suppose the class named MyClass included the following method:

- (int)getX:(int)x andY:(int)y;

Just as a reminder, this method is called getX:andY:, takes two parameters (both of them ints), and returns an int. Here's a line of code that sends a message asking a MyClass object to perform the getX:andY: method:

myNum = [myObj getX:27:50];

In this case, the object myObj (we'll see how to allocate an object in a second), presumably of class MyClass, gets sent the getX:andY: message, along with the parameters 27 and 50.

Allocating an Object

To allocate a new object, you'll send an alloc message to the class whose object you want to create. Here's an example:

id myObj = [[MyClass alloc] init];

You'll use this line of code again and again, with a few alterations of course. We start off by defining an id to hold the reference to the allocated object. The right side of the "=" operator is a message expression embedded in another method expression, much as you might embed a function call inside a second function call (printf( "%d", GetMyValue()); for example).

In this case, we are first sending the alloc message to MyClass. The alloc method is a factory method (it is declared with a leading "+" sign instead of a leading "-"), similar to a static member function in C++. It is inherited from the Object class. The alloc method allocates the memory for a single object of the specified class and returns a pointer to the object.

That object is then sent the init message, which causes that object's init method to be performed. A classes' init method should return a pointer to the object (otherwise this code wouldn't work). The object pointer returned by this nested pair of message expressions is assigned to the object pointer myObj.

As you would expect, Objective-C has an analogy to the C++ keyword "this". To refer to the current object, use the term "self". When you write your init method (to initialize your newly alloc'ed object), you'll end it by returning self:

return self;

Our First Objective-C Program

Let's bring all these concepts together with a simple example. We'll create a Number class that features a single variable, an int to hold the Number's current value. We'll add methods for initialization, one to square the Number's current value, and one to print out the current value. While this example may seem trivial, it will act as a nice syntax reference as you build your own classes.

By the time you read this, Metrowerks should have delivered their first Objective-C tools (scheduled for release as part of May's CW12). Since I don't have those tools in hand yet, I had to look at alternative Objective-C environments. As I mentioned last month, Tenon makes a Mac environment called CodeBuilder which supports the gcc Objective-C compiler. CodeBuilder supports an X environment called AfterStep, along with a more conventional unix terminal environment running either C Shell, T-C Shell (an improved C Shell), the traditional Bourne Shell (less powerful, but uses less memory), and the Bourne Again Shell (bash, Bourne Shell with improvements). All this rides on top of a Berkeley 4.4BSD unix system.

If you are into unix, CodeBuilder is definitely a lot of fun to play with. On the other hand, I find myself aching for the CodeWarrior IDE and editor to tie my projects together. Though I must admit that I did enjoy using vi to edit all my source code. Amazingly, I remembered all those cryptic vi commands that made vi such a pleasure/pain to use. Ah, well, enough reminiscing - on to the code...

The first thing I did was create a new folder to hold the source code (if you are using CodeBuilder, the unix command "mkdir dirName" creates a new directory, "cd new dir" changes directories, "mv oldname newname" changes file or directory names, "rmdir dir" deletes an empty directory, "vi filename" invokes the vi editor and "man command" brings up an online manual for the specified command. If you are new to unix or to vi, I would definitely try "man vi" to get a sense of the editor before you get into it).

Inside the new folder, I created three source files: Number.m, Number.h, and main.m. Here's the source for Number.m:

#import "Number.h"
//#include "Number.h"

(int)startValue
{
  [super init];

  value = startValue;

  return self;
}

- squareSelf
{
  value *= value;

  return self;
}

- print
{
  printf( "Number value: %d\n", value );

  return self;
}

The release of CodeBuilder I had did not support #import (at least not in the usual fashion). If your environment does not support #import, comment out that line and uncomment the #include. Remember, if you use #include, you'll need to also make a corresponding change to the header file (we'll get to it next).

Number.m contains the implementation of the Number class. All three methods are instance methods and are declared using the leading "-". Notice that the init method takes a single parameter, startValue, an int used to set the value of the instance variable named value. Value is declared in Number.h.

The init method starts off by sending an init method to its superclass (in this case, the Object class). Doing this gives your superclass a chance to initialize its superclasses and itself, a real good idea. After setting value to startValue, init returns a pointer to the newly initialized object (remember, self is like this in C++).

squareSelf and print are fairly straightforward. Note that both return self, though they don't necessarily need to, since their return value is ignored by main. Also, you can see that the C standard library function printf() is available in Objective-C. As Rhapsody starts to kick in, I'll start making use of Mac interface calls instead of using console i/o but, for now, we need to make do with what we have.

Here's the source for Number.h:

//#ifndef _Number_h_
//#define _Number_h_

#import <objc/Object.h>
//#include <objc/Object.h>


 Object
{
  int value;
}

- init:(int)startValue;
- squareSelf;
- print;

//#endif

Once again, if your environment doesn't support #import, uncomment all the commented code above and comment out the #import line. Note the declaration of the instance variable named value along with the declaration of the three methods init, squareSelf, and print. Note that all three return an id, since no return value is declared. That's why the:

return self;

at the end of each method makes sense.

Here's the source for main.m:

#include "Number.h"

void main()
{
  id number = [[Number alloc] init:27];

  [number print];

  [number squareSelf];
  [number print];

  [number free];
}

main() is just a sequence of method expressions. First, we declare number to be an object pointer, then we allocate and initialize a new Number object and assign the object's pointer (returned by init) to number. Note that the value 27 was passed in as a parameter to init. Got it?

The rest of the program is cake. Send number the print message. Here's the line of output that appears in the console window:

Number value: 27

Next, send number the squareSelf message. This causes the number object to square the value in value. Before you reach for your calculators, 27 * 27 = 729. Really.

To verify this, we pass another print message on to number. Here's the line that appears in the console window:

Number value: 729

Finally, we send the free message to number. Since the Number class does not override the Object classes' free method, the Object classes' free method is the one that ends up getting called free. The Object version of free deallocates all memory allocated for the object by alloc. Note that the Object version of free does not follow any pointers in your object to free any secondary memory. If you do allocate additional memory in your init method (don't override alloc), you'll want to override free and deallocate the additional memory.

If you do override free, be sure to send the free message to super:

[super free];

at the end of your free method to give super classes a chance to clean up after themselves.

By the way, if you are using CodeBuilder, you might want to take advantage of the unix tool called Make. Create a file called Makefile in the same directory as your sources, and type in these two lines:

Number: main.m Number.m Number.h
 gcc -o Number main.m Number.m -lobjc

Now you can recompile your program by just typing the command Make.

Till Next Month...

I am really enjoying the opportunity to mess with Objective-C. Though the syntax threw me at first, it didn't take me long before I was thinking in it. This is not a hard language. Just a bit weird! I'm definitely looking forward to getting Rhapsody up and running on my machine so I can experiment with true dynamic binding. Excellent!

Just a heads up - I have gotten a lot of email asking me to update my How to Get Started With Mac Programming article. So much has changed in the Mac universe (Rhapsody, the Internet, Objective-C, Java, etc.) that the old recommendations just don't hold water anymore. Within the next couple of months, I'm going to interrupt the Objective-C series (just for one month!) to run a new version of that article. For those of you who are already way Mac programmers, please bear with me. Till then, it's back to unix, vi, and Objective-C...

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but 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 MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
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
Amazon has clearance 9th-generation WiFi iPad...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and 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.