Morpheus
Morpheus

Reputation: 3533

specifying arguments to an Objective-C commandline app

I had made an Objective-C command line app which takes a string entered by the user. Currently I created it in such a way that it asks user at command prompt

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        printf("Enter your string: ");
        char str[11];
        scanf("%s", str);
        printf("Your string is %s\n", str);
        NSString *lastName = [NSString stringWithUTF8String:str];

        NSLog(@"lastName=%@", lastName);
    }
    return 0;
}

So when I run this program from terminal by typing programName, I will get the following:

Enter your string:

instead I would like to type something like this on terminal programName StringThatNeedsToBeneterd and it should give the same out put.

Upvotes: 0

Views: 775

Answers (1)

rob mayoff
rob mayoff

Reputation: 385660

You could use the argc and argv arguments. They provide access to the command line arguments. Many introductions to C will describe how they work.

But, since you're using Objective-C and the Foundation framework, you can use the arguments property of NSProcessInfo:

NSLog(@"arguments: %@", NSProcessInfo.processInfo.arguments);

// NSProcessInfo.processInfo.arguments[0] is the executable's name.

if (NSProcessInfo.processInfo.arguments.count > 1) {
    NSString *lastName = NSProcessInfo.processInfo.arguments[1];
}

This is nicer than using argc and argv because you get to use the Foundation types NSArray and NSString.

Upvotes: 3

Related Questions