C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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 (variaDicR_463_11845@ethodExamplE)

- (void) appendObjects:(id) firstObject,...; // This method takes a nil-terminated list of objects.

@end

@implementation NSMutableArray (variaDicR_463_11845@ethodExamplE)

- (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

大佬总结

以上是大佬教程为你收集整理的objective-c – 让自己成为一个方法,如 – [NSArray arrayWithObjects:];无限参数,由参数nil结束全部内容,希望文章能够帮你解决objective-c – 让自己成为一个方法,如 – [NSArray arrayWithObjects:];无限参数,由参数nil结束所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。