【问题标题】:Objective-c - Passing in variables to a variable-length methodObjective-c - 将变量传递给可变长度方法
【发布时间】:2011-01-26 09:54:01
【问题描述】:

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

即,我有这个(例如):

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];

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

【问题讨论】:

  • 为什么不直接传递数组呢?然后该方法将遍历数组并找出如何处理它。
  • UIAlertView 不这样做。

标签: objective-c variable-length


【解决方案1】:

-[UIAlertView initWithTitle:message:delegate:cancelButtonTitle:otherButtonTitles:]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];
}

【讨论】:

  • 按原样添加第 0 个数组对象两次,但很容易修复。
【解决方案2】:
- (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);
}

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

无论如何,... 表示法用于函数末尾的可变数量的参数。

【讨论】:

  • 参数列表末尾缺少逗号,应为- (id) initWithTitle:(NSString *)title message:(NSString *)message delegate:(id)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ...
猜你喜欢
  • 2011-05-10
  • 1970-01-01
  • 1970-01-01
  • 2011-12-07
  • 2016-04-20
  • 1970-01-01
  • 1970-01-01
  • 2012-02-09
相关资源
最近更新 更多