When using the following code to extract arguments, it works correctly for most cases, but not for IPv6 format. After a first look, seems related with the [
and ]
character that I guess have a special meaning for the parsing:
This works (szServer contains 1.2.3.4):
./myapp -address "1.2.3.4"
This does not works (szServer is nil):
./myapp -address "[2001::abc]"
I am unfortunately not fluent in objective-C, so it is probably a trivial problem, but looking at NSUserDefaults
documentation or searching on internet "NSUserDefaults with square bracket" does not bring any light (to me) on the topic.
int main(int argc, char *argv[])
{
@autoreleasepool {
NSUserDefaults *args = [NSUserDefaults standardUserDefaults];
NSString * szServer = [args stringForKey:@"address"];
}
}
I would also appreciate some clarification of what is happening.
It works if you quote the quotes in your argument:
./myapp -address '"[2001::abc]"'
For the command-line -<key> <value>
options, the value is interpreted as an old-style (NextStep-era) property list, not just as a verbatim string.
This means that one can pass arrays and dictionaries that way, for example. If you change your code to use objectForKey:
instead of stringForKey:
, it will receive an array from this:
./myapp -address '("[2001::abc]")'
Or a dictionary from this:
./myapp -address '{address="[2001::abc]";}'
Because various characters can be "special" when interpreting this format, strings have to be quoted if they have any characters outside of a limited set in them. Apparently, the left square bracket is such a character.
If you need to figure out the syntax used for a given argument, you can write a simple program which constructs an array with the desired property list object in it, and log that array. Obviously, the result will include the parentheses for formatting an array, but the object in the array will also be formatted as necessary for this old-style format. (If you didn't wrap the object in a collection like an array, then it might just write itself verbatim, as when logging an NSString
.)