Objective-C passing around … nil terminated argument lists

后端 未结 3 1816
情书的邮戳
情书的邮戳 2020-11-30 03:18

Having some issues with the ... in ObjectiveC.

I\'m basically wrapping a method and want to accept a nil terminated list and directly pass

3条回答
  •  孤街浪徒
    2020-11-30 04:05

    This is specific to the OP's UIAlertView-wrapping case, and tested only on iOS7: It appears that once a UIAlertView has been initialised with otherButtons:nil, and then has its style set to UIAlertViewStylePlainTextInput it doesn't call its delegate's alertViewShouldEnableFirstOtherButton: to validate input. I'm not sure if this is a bug or intended behaviour but it broke my principle of least astonishment. This is reproducible with the following (I'll assume the delegate's alertViewShouldEnableFirstOtherButton: is implemented):

    UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Title" 
                                                 message:@"message" 
                                                delegate:self         
                                       cancelButtonTitle:@"Cancel" 
                                       otherButtonTitles:nil];
    [av setAlertViewStyle:UIAlertViewStylePlainTextInput];
    [av addButtonWithTitle:@"OK"];
    [av show];
    

    The solution, since UIAlertView happily accepts otherButtons:nil, is to initialise UIAlertView with otherButtonTitles (which can be nil), and iterate over the variadic arguments, as above:

    + (void)showWithTitle:(NSString *)title
                  message:(NSString *)message
                 delegate:(id)delegate
        cancelButtonTitle:(NSString *)cancelButtonTitle
        otherButtonTitles:(NSString *)otherButtonTitles, ...
    {
        UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:title
                                                         message:message
                                                        delegate:delegate
                                               cancelButtonTitle:cancelButtonTitle
                                               otherButtonTitles:otherButtonTitles] autorelease];
    
        // add your [alert setAlertViewStyle:UIAlertViewStylePlainTextInput] etc. as required here
    
        if (otherButtonTitles != nil) {
            va_list args;
            va_start(args, otherButtonTitles);
            NSString * title = nil;
            while(title = va_arg(args,NSString*)) {
                [alert addButtonWithTitle:title];
            }
            va_end(args);
        }
    
        [alert show];
    }
    

提交回复
热议问题