我试图理解这样的结构:
- (void)someMethodWithArgs:(type?) param, ...
{
???
}
[self someMethodWithArgs:arg1, arg2, arg3];
答案 0 :(得分:4)
Objective-C功能的工作方式。
声明
- (void) someMethodWithArgA:(type)paramName argB:(typeB)paramNameB
{
// do something with paramName and paramNameB
}
<强>调用强>
[self someMethodWithArgA:val argB:valB];
C等价物将是:
void someMethodWithArgs(type paramName, typeB paramNameB)
{
// do something with paramName and paramNameB
}
someMethodWithArgs(val,valB);
当然,和C一样,变量类型可以是任何(为什么它们只是指针?)。
一个简单的例子:
- (int)addNum:(int)a withNum:(int)b
{
int c = a+b;
return c;
}
int k = [self addNum:2 withNum:3];
// k = 5
面向对象编程的Objective-C模型基于 消息传递给对象实例。在Objective-C中,没有 简单地调用一个方法;一个人发送消息。
http://en.wikipedia.org/wiki/Objective-C#Messages
使用可变数量的参数实现方法
#import <Cocoa/Cocoa.h>
@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.
// As many times as we can get an argument of type "id"
while (eachObject = va_arg(argumentList, id))
[self addObject: eachObject];
va_end(argumentList);
}
}
@end
来自:http://developer.apple.com/library/mac/#qa/qa1405/_index.html
答案 1 :(得分:4)
在ObjC中,参数列表语法产生C参数列表语法。
- (void) appendObjects:(id) firstObject, ...
{
id eachObject;
va_list argumentList;
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);
}
您可以在此处找到更多信息:developer.apple.com
更新:ooops,我有点晚了:)
答案 2 :(得分:1)
Matt Gallagher提供了一个关于变量参数列表的精彩教程:
Variable argument lists in Cocoa
在Apple的文档中,还有一篇关于此主题的简短技术Q&amp; A QA1405: