Johan Sørensen

Command line arguments with NSUserDefaults

Whenever I’m in need of some quick and dirty command line arguments for a simple tool, I find using NSUserDefaults to be the easiest:

$ ./mjau -input mjau.m

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

    NSString *inputFile = [[NSUserDefaults standardUserDefaults]
    NSStringEncoding usedEncoding;
    NSError *error = nil;
    NSString *content = [NSString stringWithContentsOfFile:inputFile
    if (error) {
        fprintf(stderr, "Error: %s\n",
                [[error localizedDescription] UTF8String]);
        return -1;
    fprintf(stdout, "%s\n", [content UTF8String]);

    [pool drain];
    return 0;

No need to bother with getopt(3) if you just need some simple option parsing.

Of course, this also means you can use it to set existing NSUserDefaults from the command line. One such useful toggle is the -NSShowNonLocalizedStrings YES default, turning non-localized strings into all caps making them easier to spot.