Accessing command line arguments in Objective-C

23,307

Solution 1

If all you need to do is get the command line arguments in Cocoa, you can do:

NSArray *arguments = [[NSProcessInfo processInfo] arguments];

Solution 2

You can also access the commandline arguments using NSUserDefaults as described in the blogposts by Greg Miller or Alex Rozanski.

You basically get an NSUserDefaults instance through a call to [NSUserDefaults standardUserDefaults] and then use messages like boolForKey: or stringForKey: to access the values.

The official Apple documentation can be found here.

Solution 3

As those functions are prefixed with an "_", that's usually a sign that they are private, and not meant to be used by you. If you need to get the command line arguments, a better way to do it would be to look up NSProcessInfo.

Share:
23,307

Related videos on Youtube

iPadDevloperJr
Author by

iPadDevloperJr

A new iPhone/iPad programmer

Updated on November 14, 2020

Comments

  • iPadDevloperJr
    iPadDevloperJr over 3 years

    Is there any complete documentation (the interface is present in crt_externs.h) about this functions : _NSGetArgc and _NSGetArgv I can't get any documentation on the apple website about this functions.

  • iPadDevloperJr
    iPadDevloperJr over 13 years
    Thanks i was reading this article(unixjunkie.blogspot.com/2006/07/…) and i'm just curious about this functions and their capacity to accessing command line arguments from anywhere.
  • iPadDevloperJr
    iPadDevloperJr over 13 years
    Thanks but this is just ok from the main function? not from anywhere in the program like _NSGetArgc and _NSGetArgv can do.
  • bbum
    bbum over 13 years
    Yes -- from anywhere (I'm not sure what gave you the impression that it might not be OK?).
  • s73v3r
    s73v3r over 13 years
    @Evariste Yes, you can use it anywhere. NSProcess info returns information about the current process.
  • GTAE86
    GTAE86 over 10 years
    I did not notice this answer until after I had found the post by Alex Rozanski on my own. Is any one of the methods described preferred? I am leaning towards using the NSUserDefaults because that way I do not have to parse the arguments and do things like make sure the value was not omitted. I want to make sure there is not some reason to not use teh NSUserDefaults method.
  • MKroehnert
    MKroehnert over 10 years
    I don't know if there is a preferred method. However, I am using this method to check if a commandline option is present before using it by evaluating if objectForKey: returns nil. Sample code can be found here: github.com/mkroehnert/SaneKit/blob/master/Tools/scantool.m#L‌​79
  • bugloaf
    bugloaf about 5 years
    Those documentation links are broken now. Here's what I found on the topic: developer.apple.com/library/archive/documentation/Cocoa/… Apparently there is an NSArgumentDomain specifically for command-line overrides of user preferences.