【问题标题】:How to access N number of parameters in C Function & passing the same N into next?如何访问 C 函数中的 N 个参数并将相同的 N 传递给下一个?
【发布时间】:2012-01-06 04:31:02
【问题描述】:

例如,这是我的 C ( & Objective-C ) 方法,如下所示。

void ALERT(NSString *title, NSString *message,NSString *canceBtnTitle,id delegate,NSString *otherButtonTitles, ... )
{
    // HERE I CAN ACCESS ALL THOSE ARGUMENTS
    // BUT I AM NOT SURE How to access additional arguments, supplied using ... ?

UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:title 
                                                  message:message 
                                                 delegate:delegate 
                                        cancelButtonTitle:canceBtnTitle 
                                        otherButtonTitles:// how to pass those params here?];
}

如您所见,我还必须在UIAlertViewinit 方法中传递这些参数。我不确定如何将这些参数发送到otherButtonTitles。我可以通过以下方式调用这个方法。

ALERT(@"My Alert Title",@"Alert Subtitle",@"YES",viewCtr,@"No",@"May Be",@"Cancel",nil);

ALERT(@"Alert Title",@"Alert Subtitle",@"OK",viewCtr,@"Cancel",nil);

ALERT(@"Alert Title",@"Alert Subtitle",@"OK",viewCtr,nil);

ALERT(@"Alert Title",@"Alert Subtitle",@"OK",viewCtr,@"Option1",@"Option2",nil);

【问题讨论】:

标签: objective-c c function parameters arguments


【解决方案1】:

听起来你需要了解 va_arg(以及 va_list、va_start、va_end)。

Here's a tutorial on the subject.

另外,a fine Apple tech note entitled "How can I write a method that takes a variable number of arguments, like NSString's +stringWithFormat:?"

编辑添加:

听起来你想做va_copy

啊,here is a related question

【讨论】:

  • 是的,我知道如何访问它们,但我不确定如何将它们按原样传递给问题中编辑的下一个函数。
【解决方案2】:

嗯!我已经通过Wiki link

我也从Michael' Answer in this post那里学到了一些东西。

我想出了以下解决方案。

void ALERT(NSString *title, NSString *message,NSString *canceBtnTitle,id delegate,NSString *otherButtonTitles, ... )
{
    UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:title 
                                                      message:message 
                                                     delegate:delegate 
                                            cancelButtonTitle:canceBtnTitle 
                                            otherButtonTitles:nil
                            ];

    va_list args;
    va_start(args, otherButtonTitles);
    NSString *obj;
    for (obj = otherButtonTitles; obj != nil; obj = va_arg(args, NSString*))
        [alertView addButtonWithTitle:obj];
    va_end(args);

    [alertView show];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多