objective-c - 有什么方法可以将 NSArray 传递给需要可变数量参数的方法,例如 +stringWithFormat :

标签 objective-c cocoa macos

一些上下文:我正在尝试清理我的一些 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?

相关信息:

How can I write a method that takes a variable number of arguments, like NSString's +stringWithFormat:?

最佳答案

(编辑:这可以追溯到 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/

相关文章:

ios - 如何改变 UITextField 的形状?

macos - 在持续集成中(headless env -> mac os X server),使用需要访问 GUI、xvfb/display emulator/X11 转发的工具/lib

macos - OS X 框架库未加载 : 'Image not found'

objective-c - Cocoa Mac 应用程序的一个大类与几个小类的比较

ios - 如何在 iOS 中生成 32 位 UUID?

iphone - 如何获取 iPhone 图库中的最新照片?

ios - 在 NSUserDefaults 中保存 NSdictionary

swift - 如何使用 swift 为 OS X 应用程序的标题栏着色

iphone - 所有的类方法都返回一个自动释放的对象吗?

objective-c - 指向整数的指针