Most elegant way to process command-line arguments in Cocoa?
Most elegant way to process command-line arguments in Cocoa?
- Subject: Most elegant way to process command-line arguments in Cocoa?
- From: "Diop Mercer" <email@hidden>
- Date: Wed, 7 Mar 2007 14:26:19 -0500
Hi. Is there a technique in Cocoa that someone can share that makes
processing command-line arguments as easy as in Perl?
For example, with this little bit of Perl code:
use Getopt::Std;
if (!getopts("f:t", \%args)) {
usage();
}
the following happens when you run your Perl script:
1. if -f<somestring> or -f <somestring> appears on the command line,
either is accepted. You can have a space after the argument or not,
your preference. Either way, <somestring> magically winds up in the
hash variable %args, specifically in the hash bucket $args{'f'}.
2. if -t appears on the command line, it's considered a switch, and
the hash bucket $args{'t'} gets set to 1.
Is there a Cocoa equivalent to this?
I thought I had almost found one, when I found a blog entry at:
http://unixjunkie.blogspot.com/2006/07/command-line-processing-in-cocoa.html
Greg's entry describes an elegant way to use NSUserDefaults to parse
the command line:
#import <Foundation/Foundation.h>
int main(int argc, char *argv[]) {
NSAutoreleasePool *myPool = [[NSAutoreleasePool alloc] init];
NSUserDefaults *myArgs = [NSUserDefaults standardUserDefaults];
NSLog(@"boolArg = %d", [myArgs boolForKey:@"boolArg"]);
NSLog(@"intArg = %d", [myArgs integerForKey:@"intArg"]);
NSLog(@"floatArg = %f", [myArgs floatForKey:@"floatArg"]);
NSLog(@"stringArg = %@", [myArgs stringForKey:@"stringArg"]);
[myPool release];
return 0;
}
I like the elegance of this, but it doesn't let you do switches. If
you were to run this program with:
testprog -boolArg YES
boolArg will be YES, but if you say:
testprog -boolArg
boolArg won't get set to YES. Ideally, either should work.
The other problem with this otherwise elegant solution is that it only
works when there is some space after the argument.
testprog -floatArg 2.0
works, but:
testprog -floatArg2.0
does not.
Thanks,
-m
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden