我需要在我的方法中接收多个变量Args。但我不知道该怎么做。
例如:
(void)insertInTableOnAttributes:(id)fieldsNames, ... Values:(id)fieldsValues, ...;
遗憾的是,在第一个(...)
之后出现编译错误:
Expected ':' after method Prototype".
在实施中说:
Expected Method Body" in the same position (just after the first ...)
PD:我正在使用Xcode 4.2.1。
答案 0 :(得分:5)
你做不到。生成的代码如何知道一个参数列表的结束位置和下一个参数列表的开始位置?试着想一下C等价物
void insertInTableOnAtributes(id fieldNames, ..., id fieldValues, ...);
编译器会因同样的原因拒绝该命令。
您有两个合理的选择。第一种是提供一种取代NSArray
的方法。
- (void)insertInTableOnAttributes:(NSArray *)fieldNames values:(NSArray *)fieldValues;
第二种是使用一个带有名称 - 值对的变量,类似于+[NSDictionary dictionaryWithObjectsAndKeys:]
- (void)insertInTableOnAttributes:(id)fieldName, ...;
这个将像
一样使用[obj insertInTableOnAttributes:@"firstName", @"firstValue", @"secondName", @"secondValue", nil];
C类比实际上非常准确。 Obj-C方法基本上是基于C方法的语法糖,所以
- (void)foo:(int)x bar:(NSString *)y;
由一个看起来像
的C方法支持void foobar(id self, SEL _cmd, int x, NSString *y);
除了它实际上没有真名。此C函数称为方法的IMP
,您可以使用obj-c运行时方法检索它。
如果您在varargs后面有参数,那么
- (void)someMethodWithArgs:(id)anArg, ... andMore:(id)somethingElse;
将由IMP
支持,看起来像
void someMethodWithArgsAndMore(id anArg, ..., id somethingElse);
并且因为在varargs之后你不能有任何参数,所以这根本行不通。
答案 1 :(得分:0)
- (void)insertInTableOnAttributes:(NSArray *)fieldsNames values:(NSArray *)fieldsValues;
//使用
[self insertInTableOnAttributes:[NSArray arrayWithObject:@"name", nil] values:[NSArray arrayWithObject:@"value", nil]];