Sunday, January 20, 2008

Writing my first Objective-C program

While working on the code for a future post, I needed to write a little Objective C program. The program is very simple one but I wanted to do some string processing and use some data structures such as dictionaries an arrays.

Because of this I thought it was a nice opportunity to learn a little bit about the GNUStep project. For its home page:


GNUstep is a cross-platform, object-oriented framework for desktop application development. Based on the OpenStep specification originally created by NeXT (now Apple), GNUstep enables developers to rapidly build sophisticated software by employing a large library of reusable software components.


This framework is implemented in Objective-C and it provides a lot functionality. Collections and string handling is included with this functionality. Also a lot of documentation is available in order to get started. The GNUstep documentation page provides pointers to lots of good resources.

Installation files are available from the download page. What I did was to install the gnustep-code-devel package in my Ubuntu machine, this installs all the required dependencies.

GCC, the GNU Compiler Collection includes support for Objective-C.

With all of this installed, by could start playing with Objective-C and GNUStep.

For example here's a little program that splits a string separated by commas:


#include <stdio.h>
#import <Foundation/Foundation.h>

int main(void)
{
CREATE_AUTORELEASE_POOL(pool);

NSString* aString = @"Uno ,Dos,Tres";
NSLog(aString);

NSArray *parts = [aString componentsSeparatedByString:@","];
NSString* second = [parts objectAtIndex: 1];
NSLog(second);
return 0;
}



Also the following example uses the NSMutableDictionary and NSNumber classes.


#include <stdio.h>
#import <Foundation/Foundation.h>

int main(void)
{
CREATE_AUTORELEASE_POOL(pool);
NSMutableDictionary* dictionary = [[NSMutableDictionary new] autorelease];

[dictionary setObject: [NSNumber numberWithInt: 1] forKey:@"one"];
[dictionary setObject: [NSNumber numberWithInt: 2] forKey:@"two"];


if ([dictionary objectForKey: @"one"] != nil) {
NSNumber* value = [dictionary objectForKey: @"one"];
NSLog([value stringValue]);
}

DESTROY(pool);
}


In order to compile these programs we need to create a makefile called GNUmakefile that looks like this:


include $(GNUSTEP_MAKEFILES)/common.make
TOOL_NAME = Test
LogTest_OBJC_FILES = source.m
include $(GNUSTEP_MAKEFILES)/tool.make


Here source.m is the name of the source file and Test the name of the executable.

And compile it by doing the following:


$ . /usr/share/GNUstep/Makefiles/GNUstep.sh
$ make


The GNUstep.sh sets some environment variables required by the makefile.