by ampatspell
in Code
NSUserDefaults along with it’s standard usage scenario can also be used to parse command line parameters. It’s just matter of getting shared instance and calling -stringForKey: and other methods:
#import <Foundation/Foundation.h> int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; // Get shared instance NSUserDefaults *args = [NSUserDefaults standardUserDefaults]; // Get parameters NSString *task = [args stringForKey:@"create"]; NSInteger num = [args integerForKey:@"num"]; // Do something with them if(task && num > 0) { NSLog(@"Create \"%@\" #%i", task, num); } else { NSLog(@"usage: args -create <task name> -num <number>"); } [pool drain]; return 0; }
The parameters are parsed using "-key value" semantics:
~/Cocoa/args/build/Debug$ ./args -create picture_of_the_day -num 101 2009-02-03 19:12:54.741 args[4109:10b] Create "picture_of_the_day" #101