4

我有一个包含项目的数组,我想将它们传递给一个可变长度的方法。你是怎样做的?

即,我有这个(例如):

NSArray *array = [NSArray arrayWithObjects:@"1", @"2", @"3", nil];

[[UIAlertView alloc] initWithTitle:@"title" message:@"message" delegate:nil cancelButtonTitle:[array objectAtIndex:0] otherButtonTitles:[array objectAtIndex:1], [array objectAtIndex:2], nil];

但是想象一下这个数组可能有可变长度的项目,所以你不能像这样硬编码它。

4

2 回答 2

16

otherButtonTitles参数 in的文档-[UIAlertView initWithTitle:message:delegate:cancelButtonTitle:otherButtonTitles:]指出:

使用此参数等效于使用此标题调用 addButtonWithTitle: 添加更多按钮。

你有没有试过这个:

NSArray *array = [NSArray arrayWithObjects:@"1", @"2", @"3", nil];
UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"title" message:@"message" delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:nil];
for (NSString *s in array) {
    [view addButtonWithTitle:s];
}
于 2010-03-11T14:41:32.433 回答
4
- (id) initWithTitle:(NSString *)title message:(NSString *)message delegate:(id)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles ...
{
    va_list args;
    va_start(args, otherButtonTitles);
    for (NSString *arg = otherButtonTitles; arg != nil; arg = va_arg(args, NSString*))
    {
        //do something with nsstring
    }
    va_end(args);
}

你也可以在你的函数中创建一个接受数组的参数(简单的解决方案)

无论如何, ... 符号用于函数末尾的可变数量的参数。

于 2010-03-11T14:47:37.727 回答