有没有办法将命令行选项从Xcode传递到我的iOS应用程序?

我希望能够在testing期间启动某些信息时,find一种方法将特定的信息传递给我的应用程序,以便执行特殊的debugging任务。 Xcode有一个“启动时传递的参数”部分,我假设他们会出现在我的UIApplicationDelegate的应用程序中:didFinishLaunchingWithOptions:但是传入的字典总是零。

我是否以错误的方式去做这件事?

你可以像这样使用NSProcessInfo对象来访问它们,

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

另一个更简单的方法是使用NSUserDefaults。

http://perspx.com/archives/parsing-command-line-arguments-nsuserdefaults/

从文章:

NSArgumentDomain可以parsing和使用的命令行参数必须采用以下格式:

 -name value 

参数被存储为默认的name和值的value键。 此时访问传入命令行的值与访问其他任何默认值的过程是相同的。

例如运行一个应用程序:

 MyApplication -aString "Hello, World" -anInteger 10 

允许检索命令行参数:

 NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults]; NSString *aString = [standardDefaults stringForKey:@"aString"]; NSInteger anInteger = [standardDefaults integerForKey:@"anInteger"]; 

对于那些像我这样偶然发现这个问题的人:)我想为我的静态库有一个logLevel 。 我做的是,

 static NSUInteger logLevel = 1; /** This argument should be passed from XCode's build scheme configuration option, Arguments passed on launch */ static const NSString *kIdcLogLevelArgument = @"-com.mycompany.IDCLogLevel"; @implementation IDCLogger + (instancetype)sharedInstance { static id sharedInstance = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedInstance = [[self alloc] init]; }); return sharedInstance; } +(void)initialize { logLevel = 1; NSArray *arguments = [[NSProcessInfo processInfo] arguments]; NSUInteger value = 0; if ([arguments containsObject:kIdcLogLevelArgument]) { NSUInteger index = [arguments indexOfObject:kIdcLogLevelArgument]; if (arguments.count > index) { NSString *valueStr = [arguments objectAtIndex:index + 1]; NSCharacterSet* notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet]; if ([valueStr rangeOfCharacterFromSet:notDigits].location == NSNotFound) { value = [valueStr integerValue]; logLevel = value; } } } NSLog(@"%@:logLevel = %lu", [self class], (unsigned long)logLevel); } + (void)setLogLevel:(NSUInteger)l { logLevel = l; NSLog(@"[%@]: Log level set to: %lu", [self class], (unsigned long)l); } 

除了标量之外,命令行参数可以是NSData,NSArray或NSDictionary引用。 苹果关于“旧式ASCII属性列表”的文档说明了如何去做。 https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/PropertyLists/OldStylePlists/OldStylePLists.html#//apple_ref/doc/uid/20001012-BBCBDBJE

例如,这个语法应该解码成一个NSDictionary:

MyApplication -aLocation“{latitude = 37.40089; longitude = -122.109428;}”