在Objective-C上,我可以这样做:
UIAlertView *av = [[UIAlertView alloc] initWith ... otherButtonTitles:@"button1",@"button2",nil];
我可以为自己制作一个方法,将这些参数作为参数用逗号分隔…如果是这样的话怎么样?
解决方法
在@interface中声明这样的方法:
- (id)myObjectWithObjects:(id)firstObject,... NS_REQUIRES_NIL_TERMINATION;
然后在@implementation中你会像这样定义它:
- (id)myObjectWithObjects:(id)firstObject,... { va_list args; va_start(args,firstObject); for (id arg = firstObject; arg != nil; arg = va_arg(args,id)) { // Do something with the args here } va_end(args); // Do more stuff here... }
va_list,va_start,va_arg和va_end都是用于处理变量参数的标准C语法.简单地描述它们:
> va_list – 指向变量参数列表的指针.
> va_start – 初始化va_list以指向指定参数后的第一个参数.
> va_arg – 从列表中获取下一个参数.您必须指定参数的类型(以便va_arg知道要提取的字节数).
> va_end – 释放va_list数据结构保存的所有内存.
Apple Technical Q&A QA1405 – Variable arguments in Objective-C methods的另一个例子:
@interface NSMutableArray (variadicMethodExample) - (void) appendObjects:(id) firstObject,...; // This method takes a nil-terminated list of objects. @end @implementation NSMutableArray (variadicMethodExample) - (void) appendObjects:(id) firstObject,... { id eachObject; va_list argumentList; if (firstObject) // The first argument isn't part of the varargs list,{ // so we'll handle it separately. [self addObject: firstObject]; va_start(argumentList,firstObject); // Start scanning for arguments after firstObject. while (eachObject = va_arg(argumentList,id)) // As many times as we can get an argument of type "id" [self addObject: eachObject]; // that isn't nil,add it to self's contents. va_end(argumentList); } } @end