objective-c – 让自己成为一个方法,如 – [NSArray arrayWithObjects:];无限参数,由参数nil结束

在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数据结构保存的所有内存.

查看这篇文章以获得更好的解释 – Variable argument lists in Cocoa

另见:“IEEE Std 1003.1 stdarg.h”

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

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...