一些上下文:我正在尝试清理我的一些 FMDB 代码。我的一张表有很多列,我需要使用 FMDB 中的方法,它需要可变数量的参数,类似于 NSString 的类方法 +stringWithFormat:
。
一个例子:
[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]];
当一个表只有 5 列时还不错,但是当一个列有 20 多个列时它就开始变得毛茸茸了。
我想做的是创建一个包含所有数据库抽象信息的字典并动态构建这些查询。我的问题是......在 Objective-C 中,我如何伪造出期望可变数量参数的方法,而不是将其传递给 NSArray?
相关信息:
最佳答案
(编辑:这可以追溯到 GCC 时代。从 Xcode 4.6 开始,它不在 Clang 下。)
将数组中的对象放入 C 数组中,然后将其视为可变参数列表:
//The example input array
int i = 42;
NSArray *array = [NSArray arrayWithObjects:
[NSString stringWithFormat:@"number %d", i],
[NSNumber numberWithInt:i],
[NSDate date],
[NSNumber numberWithFloat:2.2f],
nil];
//The example destination (using NSString so anyone can test this)
NSString *string = nil;
//The intermediary C array
NSObject **arrayObjects = malloc(sizeof(NSObject *) * [array count]);
if (arrayObjects) {
//Fill out the C array.
[array getObjects:arrayObjects];
//Use the C array as a va_list.
string = [[[NSString alloc] initWithFormat:@"%@ %@ %@ %@" arguments:(va_list)arrayObjects] autorelease];
free(arrayObjects);
}
NSLog(@"string: %@", string);
输出:
2009-03-26 20:10:07.128 NSArray-varargs[606:10b] string: number 42 42 2009-03-26 20:10:07 -0700 2.2
在您的情况下,您将使用 -[FMDatabase executeUpdate:arguments:]
方法。
关于objective-c - 有什么方法可以将 NSArray 传递给需要可变数量参数的方法,例如 +stringWithFormat :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/688070/