Accessing command line arguments in Objective-C
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.
Related videos on Youtube
Comments
-
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 over 13 yearsThanks 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 over 13 yearsThanks but this is just ok from the main function? not from anywhere in the program like _NSGetArgc and _NSGetArgv can do.
-
bbum over 13 yearsYes -- from anywhere (I'm not sure what gave you the impression that it might not be OK?).
-
s73v3r over 13 years@Evariste Yes, you can use it anywhere. NSProcess info returns information about the current process.
-
GTAE86 over 10 yearsI 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 over 10 yearsI 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:
returnsnil
. Sample code can be found here: github.com/mkroehnert/SaneKit/blob/master/Tools/scantool.m#L79 -
bugloaf about 5 yearsThose 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.