Parsing the command line in Objective-C

January 14th, 2009 | Tagged as , ,

Decision into which platform to rewrite the shell script to retrieve the stock quotes using Google API was a simple one – I would like to use Objective-C to be able to run the program on a Mac (and later hopefully on my iPod touch too). I began exploring the Objective-C only recently so I considered to be a good exercise to learn about basic Foundation classes by writing a class to parse command line arguments (instead of using the obvious getopt choice).


 
Download the XCode project (CommandLineSample.tar.gz, 48kB) – including a sample

 

The CommandLine class is very simple and offers the following functionality:

  • Validates and parses the command line arguments according to user defined struture of options (NSDictionary)
  • Options can be declared required or optional, followed by option value or not
  • Minimum number of expected parameters (beside options) can be set
  • When command line parsing fails, a message describing the error can be retrieved


A sample use of the CommandLine class:

#import <Foundation/Foundation.h>
#import "CommandLine.h"

int main (int argc, char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    BOOL parseSuccess;

    CommandLine *commandLine =
        [[CommandLine alloc] initWithArgc: argc andArgv: argv];

    // This sample expects at least one parameter (other that options)
    int sampleMinNumberOfParams = 1;

    // Define the matrix describing expected options
    NSDictionary *sampleOptionsMatrix =
        [NSDictionary dictionaryWithObjectsAndKeys:
            CL_OPTION_REQUIRED, @"a",
            CL_OPTION_OPTIONAL, @"b",
            CL_OPTION_REQUIRED_WITH_VALUE, @"f",
            CL_OPTION_OPTIONAL_WITH_VALUE, @"x",
            nil];

    // Pass on required parameters to the parser and execute the parser
    [commandLine cL_setOptionsMatrix: sampleOptionsMatrix
    andMinNumberOfParams: sampleMinNumberOfParams];

    parseSuccess = [commandLine cL_parse];

    if (parseSuccess) {
        // Display the parsed options.
        for (NSString *key in commandLine.parsedCommandLine) {
        NSLog(
           [NSString stringWithFormat: @"Option: %@ Value: %@", key,
           [commandLine.parsedCommandLine valueForKey:key]]);
        }
        //And some more processing of a successfully parsed command line:
        if ([commandLine cL_optionIsSet: @"b"]) {
            NSLog(@"Option b was set");
        }
        NSLog(
            [NSString stringWithFormat: @"Value of the 1st parameter is %@",
            [commandLine cL_parameterGetValue: 1]]);
    } else {
        //Display the error message
        NSLog(commandLine.resultText);
    }

    [pool drain];
    [commandLine release];

    return 0;
}

A few notes:

  • Alternative long option names are not supported
  • The options matrix appears to be somewhat verbose, hope it is not too much overhead
  • The CommandLine class source code enables some documentation to be generated using objcdoc


Feel free to use and modify the class in any way. Now off to the next step: learning the Google Data APIs Objective-C Client Library.

Your comment

You can post anonymous comments. Some tags are allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>