gpt4 book ai didi

objective-c - 方法和可选参数

转载 作者:可可西里 更新时间:2023-11-01 06:22:23 25 4
gpt4 key购买 nike

我在 Apple 文档中读到我们可以在 objective-c 方法调用中使用可选参数。 Apple 文档中的示例:

Methods that take a variable number of parameters are also possible, though they’re somewhat rare. Extra parameters are separated by commas after the end of the method name. (Unlike colons, the commas are not considered part of the name.) In the following example, the imaginary makeGroup: method is passed one required parameter (group) and three parameters that are optional:

[receiver makeGroup:group, memberOne, memberTwo, memberThree];

谁能告诉我何时使用此功能以及如何使用? Apple API 中有任何示例吗?

谢谢

最佳答案

您所描述的方法类型称为可变参数 方法。 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];
}

关于objective-c - 方法和可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11067358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com