Skip to content

Instantly share code, notes, and snippets.

@wess
Created August 14, 2012 22:28
Show Gist options
  • Save wess/3353556 to your computer and use it in GitHub Desktop.
Save wess/3353556 to your computer and use it in GitHub Desktop.
Convert command line arguments in Objective-c to an NSDictionary
// Supports --foo=bar and -f bar
static NSDictionary *arguments()
{
NSArray *arguments = [[NSProcessInfo processInfo] arguments];
if(arguments.count < 2)
return nil;
NSMutableDictionary *argsDict = [[NSMutableDictionary alloc] init];
NSMutableArray *args = [arguments mutableCopy];
[args removeObjectAtIndex:0];
NSInteger skip = 0;
for(NSString *arg in args)
{
if(skip > 0 && ((NSInteger)[arguments indexOfObject:arg]) == skip)
{
continue;
}
else
{
if([arg rangeOfString:@"="].location != NSNotFound && [arg rangeOfString:@"--"].location != NSNotFound)
{
NSArray *components = [arg componentsSeparatedByString:@"="];
NSString *key = [[components objectAtIndex:0] stringByReplacingOccurrencesOfString:@"--" withString:@""];
NSString *value = [components objectAtIndex:1];
[argsDict setObject:value forKey:key];
}
else if([arg rangeOfString:@"-"].location != NSNotFound)
{
NSInteger index = [arguments indexOfObject:arg];
NSInteger next = index + 1;
NSString *key = [arg stringByReplacingOccurrencesOfString:@"-" withString:@""];
NSString *value = [arguments objectAtIndex:next];
[argsDict setObject:value forKey:key];
}
}
}
NSLog(@"ARGS: %@", argsDict);
return [argsDict copy];
}
@jirkamatej
Copy link

  1. Does not consider variant when dashes are in the middle of the word-argument -> accept "h-elp 1"
  2. Fails when argument does not have value - access array index without check
  3. skip variable is not used

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment