Open In App

Command Line Arguments in Objective-C

Last Updated : 16 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In Objective-C, command-line arguments are strings of text that are passed to a command-line program when it is launched. They can be used to specify options or parameters that control the behavior of the program or to provide input data that the program can process.

To access command-line arguments in an Objective-C program, you can use the argc and argv variables that are passed to the main() function. argc (short for “argument count”) is an integer that specifies the number of command-line arguments passed to the program, and argv (short for “argument vector”) is an array of char pointers that points to the individual arguments.

For example, consider the following command-line invocation of a program named “main”:

./main -v input.txt output.txt

In this example, argc would be equal to 4, and argv would be an array with the following elements:

argv[0] = “./main”

argv[1] = “-v”

argv[2] = “input.txt”

argv[3] = “output.txt”

You can access the command-line arguments in your Objective-C program by iterating over the argv array and processing the individual arguments. For example:

ObjectiveC




// Objective-C program for command line argument
#import <Foundation/Foundation.h>
  
int main (int argc, const char * argv[])
{
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
        int i;
        for (i = 0; i < argc; i++)
        {
            NSString *str = [NSString stringWithUTF8String:argv[i]];
            NSLog(@"argv[%d] = '%@'", i, str);
        }
        [pool drain];
        return 0;
}


Output: 

Output of Command line arguments in Objective c

 

It’s important to note that the first element of the argv array (argv[0]) is the name of the program itself, not a command-line argument. The actual command-line arguments start at argv[1].

In addition to accessing the command-line arguments directly, you can also use the NSUserDefaults class to parse and process command-line arguments in a more convenient way. The NSUserDefaults class allows you to define a set of options and their corresponding values, and then parse the command-line arguments to extract the values of those options. This can be particularly useful if your program has a large number of command-line options, or if you want to use a consistent syntax for specifying options across multiple programs.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads