我正在开发一个可以运行该方法的命令行工具
- [NSMutableDictionary setObject:(id)object forKey:(NSString *)key]
我想传递的值是 object
是字符串的内容 argv[4]
...所以用户会输入:
mytool arg1 arg2 arg3 [NSString stringWithFormat:@"asd"]
静止,平淡argv[4]
显然是 char*
,所以我不能将其添加为 object
.
有没有办法将一个对象作为其内容的字符串转换为一个普通对象,以便我可以将它传递给上面的方法?
存在:转"[NSString stringWithFormat:@"asd"]"
进入[NSString stringWithFormat:@"asd"]
?
注意:这适用于任何 Objective-C 对象,所以我也可以传递为 argv[4]
类似 [NSArray arrayWithObjects:@"obj1", nil]
的东西.
提前致谢。
最佳答案
这是一个在运行时将 C 字符串转换为类和选择器的简单示例。
// I added arg5 and arg6 for the example
// mytool arg1 arg2 arg3 NSString stringWithFormat: asd
NSString *className = [[NSString alloc] initWithUTF8String:arg4];
NSString *selectorName = [[NSString alloc] initWithUTF8String:arg5];
NSString *argument = [[NSString alloc] initWithUTF8String:arg6];
Class myClass = NSClassFromString(className);
SEL mySelector = NSSelectorFromString(selectorName);
// If arg5 is a class method
[myClass performSelector:mySelector withObject:argument];
// or if arg5 is an instance method
id instance = [[myClass alloc] init];
[instance performSelector:mySelector withObject:argument];
这是一个包含三个标记的简单示例:NSString
、stringWithFormat:
和一个参数。要处理更复杂的情况,您需要编写自己的字符串解析器。不过,它向您展示了一些可能性。
关于objective-c - "Unstring"一个 Objective-C 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7748629/