Created
August 14, 2012 22:28
-
-
Save wess/3353556 to your computer and use it in GitHub Desktop.
Convert command line arguments in Objective-c to an NSDictionary
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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
commented
May 11, 2021
- Does not consider variant when dashes are in the middle of the word-argument -> accept "h-elp 1"
- Fails when argument does not have value - access array index without check
- skip variable is not used
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment