可变参数函数(stdarg.h)的使用

2013/5/3记录:

stdarg.h是C语言中C标准函数库的头文件,stdarg是由standard(标准) arguments(参数)简化而来,主要目的为让函数能够接收可变参数。
 

stdarg.h数据类型

类型名称
描述
相容
va_list
用来保存宏va_arg与宏va_end所需信息
C89

stdarg.h宏

巨集名称
描述
相容
va_start
使va_list指向起始的参数
C89
va_arg
检索参数
C89
va_end
释放va_list
C89
va_copy
拷贝va_list的内容
C99
C99提供额外的宏,va_copy,它能够复制va_list。而va_copy(va2, va1)函数作用为拷贝va1到va2。

 

访问未命名的参数,首先必须在可变参数函数中声明va_list类型的变量。
调用 va_start并传入两个参数:第一个参数为va_list类型的变量,第二个为省略号前最后一个有名字的参数的名称;
接着每一调用va_arg就会返回下一个参数,va_arg的第一个参数为va_list,第二个参数为返回的类型。
最后va_end必须在函数返回前被va_list调用(va_list当作参数)(没有要求要读取完所有参数)。
 
 
 
使用例子:(自定义多按钮AlertView):
- (void)showAlert:(id)sender Title:(NSString*)title Message:(NSString*)message cancelButton:(NSString*)cancelbutton otherButton:(NSString*)otherbutton,... {
   
   UIAlertView*alert = [[UIAlertViewalloc] initWithTitle:title
                                                    message:message
                                                   delegate:sender
                                          cancelButtonTitle:cancelbutton
                                          otherButtonTitles:otherbutton,nil];
    id eachObject;
va_list argumentList;
if (otherbutton)
    {
        va_start(argumentList, otherbutton);
        while ((eachObject = va_arg(argumentList, id)))
        {
            NSString *str = [NSStringstringWithFormat:@"%@",eachObject];
            [alert addButtonWithTitle:str];
        }
        va_end(argumentList);
    }
    [alert show];
    [alert release];
}
 

猜你喜欢

转载自www.cnblogs.com/ios-wmm/p/10215063.html