Command Line Arguments in Detail
In Objective-C, command-line arguments are text strings passed to a program when it runs from the command line. They provide input parameters or options that control the program’s behavior or supply data for processing.
The main function of an Objective-C program receives two parameters: argc and argv.
argc(short for “argument count”) is an integer representing the number of arguments passed to the program.argv(short for “argument vector”) is an array ofcharpointers, each pointing to a command-line argument.
./example -debug config.json output.log
In this case:
1. argc will be 4, as there are four arguments.
2. argv will hold the following values:
- argv[0] = “./example”
- argv[1] = “-debug”
- argv[2] = “config.json”
- argv[3] = “output.log”
Example 1:
// Objective-C program to demonstrate command-line arguments
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
for (int i = 0; i < argc; i++)
{
NSString *arg = [NSString stringWithUTF8String:argv[i]];
NSLog(@"Argument %d: %@", i, arg);
}
[pool drain];
return 0;
}
Output:
./example -debug config.json output.log
The output will be:
Argument 0: ./example
Argument 1: -debug
Argument 2: config.json
Argument 3: output.log
Leave a Reply