开发者

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.

开发者_StackOverflow

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


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


There isn't a general way to do this, but for UIActionSheet specifically, you don't need to use that constructor.

UIActionSheet *sheet = [[UIActionSheet alloc] init];

// set properties
sheet.title = @"Title!";

// add buttons
for (NSString *buttonTitle in otherButtonTitles) {
    [sheet addButtonWithTitle:buttonTitle];
}

sheet.cancelButtonIndex =
    [sheet addButtonWithTitle:@"Cancel"];

UIAlertView can be initialized in a similar way.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜