Objective-c - Passing in variables to a variable-length method

老子叫甜甜 提交于 2019-12-01 21:38:04

问题


I've got an array with items, and I want to pass these in to a variable-length method. How do you do that?

I.e., I've got this (for example):

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

But imagine that array could have a variable length of items, so you cant hardcode it like this.


回答1:


The documentation for the otherButtonTitles parameter in -[UIAlertView initWithTitle:message:delegate:cancelButtonTitle:otherButtonTitles:] states that:

Using this argument is equivalent to invoking addButtonWithTitle: with this title to add more buttons.

Have you tried this:

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



回答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);
}

You could also just make an argument in your functions that accepts an array (easy solution)

Anyway the ... notation is for a variable amount of arguments at the end of a function.



来源:https://stackoverflow.com/questions/2425732/objective-c-passing-in-variables-to-a-variable-length-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!