Search code examples
objective-cnsarrayvariadic-functions

How to pass elements of an array to variadic function?


I'm sure this must be answered somewhere already but I'm struggling to find the right search terms for the answer.

In my objective-c code I have an NSArray of an unknown number strings that I want to pass its elements to a variadic init method, in this case its the ... list of 'otherButtonTitles' in the constructer of UIActionSheet. How can this be achieved?

thanks in advance


Solution

  • I think you would need to pass the first element of the array to the constructor and then use the addButtonWithTitle method to loop through the remaining elements and add them:

    UIActionSheet *mySheet = [[UIActionSheet alloc] initWithTitle:title delegate:delegate cancelButtonTitle:cancelButtonTitle destructiveButtonTitle:destructiveButtonTitle otherButtonTitles:[myOtherButtons objectAtIndex:0],nil];
    
    NSMutableArray *otherbuttons = myOtherButtons;
    [otherButtons removeObjectAtIndex:0];
    
    NSEnumerator *enumerator = [otherButtons objectEnumerator];
    id anObject;
    
    while (title = [enumerator nextObject]) {
        [mySheet addButtonWithTitle:title];
    }