Post

Replies

Boosts

Views

Activity

Strange behaviour of command line arguments in iOS/Objective-C
I noticed a strange problem on iOS. Consider this code: #import <Foundation/Foundation.h> #include <fstream> #include <string> #include <iostream> #include <vector> int main(int argc, char * argv[]) { &#9;&#9;NSArray* args = NSProcessInfo.processInfo.arguments; &#9;&#9;for(int i = 0; i < args.count; ++i) &#9;&#9;{ &#9;&#9;&#9;&#9;std::cout<<"Arg "<<i<<" "<<[args[i] UTF8String] <<std::endl;&#9;&#9; &#9;&#9;} &#9;&#9;NSArray<NSURL *> *urls = &#9;&#9;&#9;&#9;[[NSFileManager defaultManager] &#9;&#9;&#9;&#9;&#9;&#9;URLsForDirectory:NSDocumentDirectory &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; inDomains:NSUserDomainMask];&#9; &#9;&#9;NSString *filename = [[urls[0] path] &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; stringByAppendingString: @"/file.txt"];&#9; &#9; &#9;&#9;std::ofstream f1([filename UTF8String], std::ios::trunc);&#9;&#9; &#9;&#9;if(args.count > 3) &#9;&#9;{ &#9;&#9;&#9;&#9;std::cout<<"More than 3 args"<<std::endl; &#9;&#9;&#9;&#9;f1<<"More than 3 args"<<std::endl; &#9;&#9;} &#9;&#9;else &#9;&#9;{ &#9;&#9;&#9;&#9;std::cout<<"Less or equal to 3 args"<<std::endl; &#9;&#9;&#9;&#9;f1<<"Less or equal to 3 args"<<std::endl; &#9;&#9;} } It checks the number of command line arguments. If it is larger than 3 prints a message to console and to a file. Else outputs a different message. I set the input arguments by editing Xcode scheme. Here is the console output when I pass more than 3 input args: Arg 0 /var/containers/Bundle/Application/6354AF7F-6817-423D-88FD-976813627552/CLIArgTest.app/CLIArgTest Arg 1 hrhtrnd Arg 2 ebyrebyes Arg 3 fvtrvter Arg 4 jvojeojgreo More than 3 args However, when I extract the output file from the on device Document folder of the iOS app, I get: Less or equal to 3 args I don’t get this problem if I run the exact same code on MacOS. I tried building both debug and release and it makes no difference. I tried writing to file using ObjC and C++ API, no difference. I tried using argc/argv directly instead of NSProcessInfo.processInfo.arguments, no difference. I couldn’t find any references to this problem online. Although admittedly very few people do this type of command line based dev on iOS. The reason I need to do this is because I am trying to build a unit testing app around a library I wrote and I would like to control some test parameters using command line arguments.
2
0
896
Sep ’20