Other methods of Command-Line arguments


#1

I did some experimenting and found there are several other ways to handle arguments.

One is to use the defaults system and the NSArgumentDomain. This is pretty cool as it requires almost no code at all to implement. The arguments can then be looked up with KVC.

The other method is to use NSProcessInfo and its arguments method. This returns an NSArray of the arguments that you can then pick over.

I put together some simple code to show how they both work. The arguments in this case are -name -times

[code]#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{

@autoreleasepool {
    
    // First lets use the defaults system
    
    NSLog(@"Finding args with the defaults system");
    NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
    
    NSString *aString = [standardDefaults stringForKey:@"name"];
    NSInteger anInteger = [standardDefaults integerForKey:@"times"];
    
    for (int i = 0; i < anInteger; i++) {
        NSLog (@"%@ is cool!", aString);
    }
    
    //Now using the process info
    
    NSLog(@"\n\nFinding args with the defaults system");

    NSArray *args = [[NSProcessInfo processInfo] arguments];
    
    int nameCount = [[args objectAtIndex:4] intValue];
    
    for (int i = 0; i < nameCount ; i++) {
        NSLog (@"%@ is cool!", [args objectAtIndex:2]);
    }
    
}
return 0;

}
[/code]


#2

Thanks. Processing CLI arguments is a pain in any language, glad to see there are some useful mechanisms.

Beats the heck out of GNU getopt.


#3

Oh yeah it does. Better than scanf too.

I like that with the NSArgumentDomain you have a lot of flexibility. Args can be in any order and it’s easy to validate that you have them because it works with KVC.


#4

Unless you are actually passing arguments to main(), you don’t need to include them at all. I just use int main() and everything has always run without problems. Saves on the typing. At least in my experience.


#5

Have you offer something like this again.