44

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
  • 932
  • 3
  • 19
  • 33

3 Answers3

84

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

NSArray *arguments = [[NSProcessInfo processInfo] arguments];
Wevah
  • 28,020
  • 7
  • 84
  • 72
  • 2
    Thanks but this is just ok from the main function? not from anywhere in the program like _NSGetArgc and _NSGetArgv can do. – iPadDevloperJr Feb 28 '11 at 20:25
  • 2
    Yes -- from anywhere (I'm not sure what gave you the impression that it might not be OK?). – bbum Feb 28 '11 at 21:02
26

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.

MKroehnert
  • 3,518
  • 2
  • 31
  • 42
  • 1
    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. – GTAE86 Jan 15 '14 at 17:00
  • 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: https://github.com/mkroehnert/SaneKit/blob/master/Tools/scantool.m#L79 – MKroehnert Jan 18 '14 at 09:50
  • Those documentation links are broken now. Here's what I found on the topic: https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/UserDefaults/AboutPreferenceDomains/AboutPreferenceDomains.html#//apple_ref/doc/uid/10000059i-CH2-96930 Apparently there is an NSArgumentDomain specifically for command-line overrides of user preferences. – bugloaf Apr 29 '19 at 15:48
7

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.

s73v3r
  • 1,721
  • 2
  • 21
  • 47
  • Thanks i was reading this article(http://unixjunkie.blogspot.com/2006/07/access-argc-and-argv-from-anywhere.html) and i'm just curious about this functions and their capacity to accessing command line arguments from anywhere. – iPadDevloperJr Feb 28 '11 at 20:01
  • @Evariste Yes, you can use it anywhere. NSProcess info returns information about the current process. – s73v3r Mar 01 '11 at 01:08