您描述的方法类型称为可变参数方法。Cocoa 中的示例包括+[NSArray arrayWithObjects:]
和+[NSDictionary dictionaryWithObjectsAndKeys:]
。您可以使用定义在stdarg.h
.
+[NSArray arrayWithObjects:]
以下是如何实现该方法的示例:
+ (NSArray *)arrayWithObjects:(id)firstObject, ... {
int count = 0;
va_list ap;
va_start(ap, firstObject);
id object = firstObject;
while (object) {
++count;
object = va_arg(ap, id);
}
va_end(ap);
id objects[count];
va_start(ap, firstObject);
object = firstObject;
for (int i = 0; i < count; ++i) {
objects[i] = object;
object = va_arg(ap, id);
}
va_end(ap);
return [self arrayWithObjects:objects count:count];
}