objective-c – 让自己成为一个方法,如 – [NSArray arrayWithOb
发布时间:2020-12-16 05:42:06 所属栏目:百科 来源:网络整理
导读:在Objective-C上,我可以这样做: UIAlertView *av = [[UIAlertView alloc] initWith ... otherButtonTitles:@"button1",@"button2",nil]; 我可以为自己制作一个方法,将这些参数作为参数用逗号分隔…如果是这样的话怎么样? 解决方法 在@interface中声明这样
在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 – 指向变量参数列表的指针. 查看这篇文章以获得更好的解释 – 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |