Command Line Flags in Objective-C
Here’s the translation of the Go code to Objective-C, with explanations in Markdown format suitable for Hugo:
Our first program will demonstrate how to handle command-line flags in Objective-C. Here’s the full source code:
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSString *word = @"foo";
NSInteger numb = 42;
BOOL fork = NO;
NSString *svar = @"bar";
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults stringForKey:@"word"]) {
word = [defaults stringForKey:@"word"];
}
if ([defaults objectForKey:@"numb"]) {
numb = [defaults integerForKey:@"numb"];
}
if ([defaults objectForKey:@"fork"]) {
fork = [defaults boolForKey:@"fork"];
}
if ([defaults stringForKey:@"svar"]) {
svar = [defaults stringForKey:@"svar"];
}
NSLog(@"word: %@", word);
NSLog(@"numb: %ld", (long)numb);
NSLog(@"fork: %@", fork ? @"YES" : @"NO");
NSLog(@"svar: %@", svar);
NSArray *arguments = [[NSProcessInfo processInfo] arguments];
NSLog(@"tail: %@", [arguments subarrayWithRange:NSMakeRange(1, arguments.count - 1)]);
}
return 0;
}
In Objective-C, we don’t have a built-in flag parsing library like Go’s flag
package. Instead, we can use NSUserDefaults
to handle command-line arguments. This approach is not as robust as Go’s flag package, but it provides a simple way to handle basic command-line options.
We start by setting default values for our options. Then, we use NSUserDefaults
to check if any of these options were provided as command-line arguments.
After parsing the arguments, we print out the values of all options using NSLog
.
To handle trailing arguments, we use NSProcessInfo
to get all command-line arguments and then create a subarray excluding the first argument (which is the program name).
To compile and run this program:
$ clang -framework Foundation CommandLineFlags.m -o CommandLineFlags
$ ./CommandLineFlags
word: foo
numb: 42
fork: NO
svar: bar
tail: ()
You can provide command-line arguments like this:
$ ./CommandLineFlags -word opt -numb 7 -fork YES -svar flag
word: opt
numb: 7
fork: YES
svar: flag
tail: ()
Note that this simple implementation doesn’t provide automatic help text generation or proper error handling for invalid flags. In a real-world application, you might want to use a more robust command-line parsing library for Objective-C, such as ArgumentParser
or implement more comprehensive argument parsing yourself.
Also, unlike Go, Objective-C doesn’t have a built-in way to specify the type and description of each flag. If you need this functionality, you would need to implement it yourself or use a third-party library.