Command Line Arguments in Objective-C

Our first program demonstrates how to work with command-line arguments. Here’s the full source code:

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // NSProcessInfo provides access to command-line arguments
        NSArray *args = [[NSProcessInfo processInfo] arguments];
        
        // The first argument is the program path
        NSArray *argsWithoutProg = [args subarrayWithRange:NSMakeRange(1, [args count] - 1)];
        
        // You can get individual args with normal indexing
        NSString *arg = args[3];
        
        NSLog(@"%@", args);
        NSLog(@"%@", argsWithoutProg);
        NSLog(@"%@", arg);
    }
    return 0;
}

NSProcessInfo provides access to command-line arguments. Note that the first value in this array is the path to the program, and [args subarrayWithRange:NSMakeRange(1, [args count] - 1)] holds the arguments to the program.

You can get individual args with normal indexing.

To experiment with command-line arguments, it’s best to compile the program first:

$ clang -framework Foundation command_line_arguments.m -o command_line_arguments
$ ./command_line_arguments a b c d
2023-06-11 12:34:56.789 command_line_arguments[1234:56789] (
    "/path/to/command_line_arguments",
    a,
    b,
    c,
    d
)
2023-06-11 12:34:56.789 command_line_arguments[1234:56789] (
    a,
    b,
    c,
    d
)
2023-06-11 12:34:56.789 command_line_arguments[1234:56789] c

Next, we’ll look at more advanced command-line processing with options or flags.