Objective-C First Program


Today I will walk you through your first Objective-C program. It is important to note I am not going to explain how to run this code on any platform. This is Objective-C using the Foundation framework that supplies classes like NSString and NSLog. I will create a tutorial later on how to run Objective-C code on Windows but not other platforms. That being said our first program is going to be really simple. It will involve two classes, one will be the main class that holds the main method and the other is an object class. The point of this program is to call different methods in the object class and from an Object of this class, to print out different things. I will also go over some typical things a programmer does like iterate through an array.

First the Syntax:

While I have covered the general program structure of Objective-C before I’m going to go into more detail on class and method declaration in both the header and implementation files.

As you may recall the first line of the header file includes the @interface tag and the class name. The complete syntax is this:

@interface className: superClass

This is pretty self-explanatory. Instead of Java’s extends key word Objective-C uses a ‘:’. In the implementation file all you’ll need as a first line is this:

@implementation headerFileClassName

So if I had a header file:

@interface Box: NSObject

The implementation would be:

@implementation Box

Simple right? Right. Note that the @interface and @implementation tags are ended with a @end tag.

On to methods. Note that the +- signs in the {} mean either or could go there. I will explain their meaning later.

{+-}(returnType) methodName : (argumentType) argName partTwo: (argumentType2) argName2 ..

This is what you will write in both the header and implementation files, the implementation will simply have the actual code for the method in {} beneath the declaration. Methods denoted with a ‘+’ are static or class level methods while those with a ‘-’ are instance level methods. What can get really confusing with Objective-C methods is the “partTwo” or joiningArgumentDescription. This part of the method declaration is run together with all other joingingArguments and the method name when calling that method so the method name is incredibly descriptive. For example I have an instance method that finds the area of a box with a specified length and width this is how I would write that:

- (double) calculateAreafromWidth: (double) w andLength: (double) l;

So the method call would be

[Box calculateAreafromWidth: 5.0 andLength: 2.0]; 

Ignoring the grammar the method call becomes very descriptive of what it is doing.

Moving on. Header file

So only our object class is going to have a header file a main class does not need an interface to describe it and is also not being imported by any other classes. So with that established here we go:

#import <Foundation/Foundation.h> //Import the Foundation framework.
@interface Speaker: NSObject //Speaker class extends NSObject. (In Java we would leave this out. The equivalent being … extends Object)
//Class level/ Static method
+ (void) speak; //Class level hello
//Instance level methods (public)
- (void) hello; //Will print out Hello
- (void) helloPerson :( NSString) name; //hello name
- (void) helloPerson :( NSString) name withLastName: (NSString) lastName; //hello name, lastName
- (void) printListByIndex; //hello: elm1, elm2, elm3,
- (void) printListByEnumeration; //hello: elm1, elm2, elm3,
- (void) decision: (int) num; //give 1, 2, 3 and get different things.

Our class Speaker has no locally global variables so all you see are the methods I will implement.

Speaker.m file

Here I am going to define all the methods I declared in the header file. Explanations will be in the code so make sure to read the comments!

#import “Speaker.h” //import Speaker header file.
@implementation Speaker
+ (void) speak {
The easiest way to create an NSString is by creating a ‘static’ instance of it using the @”…” construct. For example,
NSString *name = @”Nicola”;
name will point then to a ‘static’ instance of NSString containing a Unicode representation of the ASCII string Nicola. A ‘static’ instance basically means an instance which is allocated at compile time, whose instance variables are fixed, and which can never be released.
//Instance level methods (public)
- (void) hello{
- (void) helloPerson:(NSString) name;{ //hello name
NSString *sentence; //Strongly typed local variable
sentence = [NSString stringWithFormat: @”Hello %@ nice to meet you.”, name]; //replace %@ with name
//The same thing could have been done as follows: NSLog(@”Hello %@ nice to meet you.”,name);
- (void) helloPerson:(NSString) name withLastName: (NSString) lastName;{ //hello name, lastName
NSLog(@”Hello %@ %@ nice to meet you.”,name, lastName);
- (void) printListByIndex;{ //hello: elm1, elm2, elm3,
NSArray *names;
names = [NSArray arrayWithObjects: @”Abe Abberly”, @”Bob Barker”, @”Carl Carsten”, nil];
//The last element of an array must be nil to denote the end. Much like how C arrays end with a null.
// arrayWithObjects allows you to put Objects in an array instead of just simple data types like int.
//Note arrays can hold a mix of Objects not just one kind. For example I could add an array to an array with strings in it.
int i, count; //declare both i and count
count = [names count]; //get the number of elements in names
for (i = 0; i < count; i++)
NSLog(@”Hello %@ you are the %d person in the list”, [array objectAtIndex: i], i);
- (void) printListByEnumeration{ //Moving through an array by index isn’t the only way.
NSEnumerator *enumerator;
NSObject *obj;
enumerator = [array objectEnumerator]; //objectEnumerator will return a NSEnumerator which can be used to step through the array
while ((obj = [enumerator nextObject]) != nil)
NSLog (@”Hello %@”, obj);
- (void) decision: (int) num{ //give 1, 2, 3 and get different things.
if(num == 1)
NSLog (@”Hello Number One. You are GOLDEN.”);
else if(num == 2)
NSLog (@”Hello Number Two. You see the SILVER lining.”);
else if (num == 3)
NSLog (@”Hello Number Three. You are looking statuesque in BRONZE.”);
NSLog (@”Hey I said choose a number that is 1 OR 2 OR 3");
@end //End implementation.

There is the implementation. Not so different from Java.

main.m file

Here’s the fun part. Main doesn’t have a header file because it’s not needed as I stated earlier. Main also looks a bit different than any of the other methods we’ve seen. No @implementation tag on this file either. Just let it go, the universe needs no reason.

#import <Foundation/Foundation.h>
#import “Speaker.h”
int main(int argc, const char * argv[]) { //Remind you of C anyone? 
//int argc is the number of arguments in argv
//argv is a constant strongly typed char array that holds the values of the arguments passed into main.
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; //Just a memory managment tool. It does wat you think it does.
Speaker speaker = [[Speaker alloc] init]; //alloc allocates memory, init is the ‘constructor’ for the class
[Speaker speak];
[speaker hello];
[speaker helloPerson: @”World”];
[speaker helloPerson: @”World” withLastName: @”Destruction”]; //I’m kidding
/*- (void) printListByIndex; //hello: elm1, elm2, elm3,
— (void) printListByEnumeration; //hello: elm1, elm2, elm3,
— (void) decision: (int) num; //give 1, 2, 3 and get different things.*/
[speaker printListByIndex];
[speaker printListByEnumeration];
for(int i = 1; i <= 4; i++)
[speaker decision: i];
[pool drain]; //release everything

There! We’re done! Now you should know how to make a class, instantiate an Object and create a Main method. Next blog I’ll walk through compiling and running this code on a Windows machine as well as go into a bit more detail on the Frameworks.

References and further reading below.


Further Reading: