Define a method that has many (or infinite) arguments(定义具有许多(或无限)参数的方法)
问题描述
NSArray
的 initWithObjects:
方法接受一个不确定的参数列表:
The initWithObjects:
method of NSArray
takes an indefinite list of arguments:
NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:(id), ..., nil
我怎样才能像这样定义自己的方法?
How can I define my own method like this?
- (void)CustomMethod:????? <= want to take infinite arguments {
}
推荐答案
无限参数"是可变参数,使用它们的方法称为可变参数方法.您定义它们的方式与您的 NSMutableArray
示例相同.苹果的技术问答有一个例子说明如何实现它.
The "infinite arguments" are variable arguments and the methods that use them are called variadic methods. You define them the same way as your NSMutableArray
example. Apple's Technical Q&A has an example of how to implement it.
- (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);
}
}
nil
参数的原因是为了让您知道何时到达列表末尾.NSLog
和 printf
等函数不需要最后一个参数为 nil
,因为它可以计算格式字符串(%d
、%s
等...)
The reason for the nil
argument is so that you know when you have reached the end of the list. Functions like NSLog
and printf
do not require the last argument to be nil
because it can count the number of specifiers in the format string (%d
, %s
etc...)
这篇关于定义具有许多(或无限)参数的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:定义具有许多(或无限)参数的方法
基础教程推荐
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01