是否可以在Obj-c中为可变参数函数发送数组?

是否可以在Obj-c中为可变参数函数发送数组?

问题描述:

在python中,很容易构建字典或数组并将其解压缩后传递给具有可变参数的函数

In python it is easy to build a dictionary or array and pass it unpacked to a function with variable parameters

我有这个:

- (BOOL) executeUpdate:(NSString*)sql, ... {

手动方式是这样的:

[db executeUpdate:@"insert into test (a, b, c, d, e) values (?, ?, ?, ?, ?)" ,
  @"hi'", // look!  I put in a ', and I'm not escaping it!
  [NSString stringWithFormat:@"number %d", i],
  [NSNumber numberWithInt:i],
  [NSDate date],
  [NSNumber numberWithFloat:2.2f]];

但是我无法对要调用的参数进行硬编码,

But I can't hardcode the parameters I'm calling, I want:

NSMutableArray *values = [NSMutableArray array];

for (NSString *fieldName in props) {
  ..
  ..
  [values addObject : value]
}
[db executeUpdate:@"insert into test (a, b, c, d, e) values (?, ?, ?, ?, ?)" ,??values];

不幸的是,没有.与使用许多现代语言一样,Objective-C不需要打开参数.我从未发现过解决此问题的好方法.

Unfortunately, no. Objective-C doesn't have argument unpacking like you get in a lot of modern languages. There isn't even a good way to work around it that I've ever found.

部分问题是,Objective-C本质上只是C.它使用C varargs传递多个参数,并且没有简单的方法来使用varargs. 相关的SO讨论.

Part of the problem is that Objective-C is essentially just C. It does multiple argument passing with C varargs, and there's no simple way to do this with varargs. A relevant SO discussion.