codescracker


objective c

Objective-C Command Line Arguments



« Previous Tutorial Next Tutorial »


You are free to create an Objective-C program, so that you can pass some values from the command line to your Objective-C programs at the time of execution of the program. These passed values are called as the command line arguments and they are important for your program many times, mainly when you want to control your program at the run-time or from outside instead when writing the program

Objective-C Command Line Arguments Example

The command line arguments in Objective-C are handled using the main() function arguments, where the argc represents to the total number of arguments passed, and the argv[] represents a pointer array, which points to each argument passed to the program. Here is an example program, demonstrating the concept of command line argument in Objective-C practically. This program checks if there is any argument supplied from the command line and then takes the action accordingly:

/* Objective-C Command Line Arguments - Example Program */
		
#import <Foundation/Foundation.h>
int main(int argc, char *argv[])  
{
	if(argc == 2)
	{
		NSLog(@"The supplied argument = %s\n", argv[1]);
	}
	else if(argc > 2)
	{
		NSLog(@"Too many arguments supplied!\n");
	}
	else
	{
		NSLog(@"One argument expected!\n");
	}
	return 0;
}

When the above code is compile and executed with a single argument, say "testing", then it will produce the following result:

2014-10-03 13:18:37.932 demo[7640] The argument supplied is testing

Now, when the above code is compile and executed with two arguments, say testing1 and testing2, then it will produce the following result:

2014-10-03 13:18:37.932 demo[7640] Too many arguments supplied!

And, when the above code is compile and executed without passing any argument, then it will produce the following result

2014-10-03 13:18:37.932 demo[7640] One argument expected!

As you can see from the above Objective-C program and outputs, that argv[0] holds the name of the program itself and argv[1] is a pointer to the first command-line argument supplied, and *argv[n] is the last argument.


« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test