Objective-C for C programmers

Anyone from a C background like me will find parts of Objective-C—Apple’s primary development language—nigh-on indecipherable.  It’s an amalgam of C and Smalltalk which appeared in 1983.  It seems to have been developed around the same time as C++, but for my money Bjarne Stroustrup et al did a better job.  Maybe I’m comparing Apples and Oranges (apologies for the pun).

Fortunately a helpful man by the name of Tristan O’Tierney has written a very good introduction to Objective C for C programmers.  However he doesn’t mention how to compile Objective C using the command line.

Compiling Objective C from the command line

I’m afraid I’m the computer equivalent of a survivalist and always like to know where possible how to revert to the simplest form.  Here’s a Scripting Bridge example which is derived from code on Stack Overflow.

#import <Foundation/NSString.h>
#import <Foundation/NSAutoreleasePool.h>
#import <stdio.h>
#import "Finder.h"

int main(int argc,const char *argv[])
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    FinderApplication *finder = [SBApplication applicationWithBundleIdentifier:@"com.apple.finder"];

    SBElementArray *windows = [finder windows ]; // array of finder windows
   NSArray *targetArray = [windows arrayByApplyingSelector:@selector(target)];// array of targets of the windows

    //gets the first object from the targetArray,gets its URL, and converts it to a posix path
    NSString *newURLString = [[NSURL URLWithString: (id) [[targetArray objectAtIndex:0]URL]] path];

    printf("POSIX path for first Finder window: %s\n",[newURLString UTF8String]) ;

    [pool drain] ;
}

This can be compiled on the command line like this:

cc -Wall -O -l objc -framework Foundation -framework ScriptingBridge ScrBridge.m -o ScrBridge

The key parts of that command line are the framework options.  Now, I’ll concede that as applications get more complicated you need a development environment, such as Xcode, and of course it is all but impossible to do any but the most trivial graphical applications without such an environment.  But for systems programming I’ll stick with the command line for as long as possible.

Leave a Reply

Your email address will not be published. Required fields are marked *