Forward variadic arguments for a UIAlertView

ぃ、小莉子 提交于 2019-12-22 10:44:10

问题


I'm trying to set up a very simple UIAlertView with a text edit, an Ok and a cancel button, and I want to disable the Ok button based on the content of the text edit.

To be able to retain the delegate so that he doesn't go away before the alert view (and thus cause a crash as soon as the user does something with the alert view), I've subclassed it. Now, I want to be able to forward the otherButtonTitles argument from my init method to the UIAlertView init method, but for some reasons, simply doing that:

- (id)initWithTitle:(NSString *)title
            message:(NSString*)message
           delegate:(id /*<UIAlertViewDelegate>*/)delegate
  cancelButtonTitle:(NSString *)cancelButtonTitle
  otherButtonTitles:(NSString *)otherButtonTitles, ... {

    if (self = [super initWithTitle:title 
                            message:message 
                           delegate:delegate 
                  cancelButtonTitle:cancelButtonTitle 
                  otherButtonTitles:otherButtonTitles, nil]) {
        //stuff
    }

only adds the first element of the args to the alert view. I've found that I can actually manually add the buttons to the alert view using this:

va_list args;
va_start(args, otherButtonTitles);
for (NSString *buttonTitle = otherButtonTitles; buttonTitle != nil; buttonTitle = va_arg(args, NSString*)) {
  [self addButtonWithTitle:buttonTitle];
}
va_end(args);

but then, my alertViewShouldEnableFirstOtherButton delegate method isn't called anymore, with the probable explanation in this post.

Thus, how can I forward correctly my otherButtonTitles to the UIAlertView init method correctly?


回答1:


Let's reduce keystrokes then:

NSMutableArray *otherButtonTitles = [NSMutableArray array];
// .. collect varargs into ^^^

#define T(n) ([otherButtonTitles objectAtIndex:n])
#define CASE(n, ...) case n: self = [super initWithTitle:title \
                                                 message:message \ 
                                                delegate:delegate \
                                       cancelButtonTitle:cancelButtonTitle \
                                       otherButtonTitles:__VA_ARGS__, nil]; \
                             break

switch ([otherButtonTitles count]) {
    CASE(0, nil);
    CASE(1, T(0));
    CASE(2, T(0), T(1));
    CASE(3, T(0), T(1), T(2));
    // ... repeat until bored ...
    default: @throw @"too many buttons"; // or return nil
}


来源:https://stackoverflow.com/questions/26102660/forward-variadic-arguments-for-a-uialertview

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