S.J*_*Lim 8 syntax arguments objective-c
该initWithObjects:方法NSArray采用的参数不确定的列表:
NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:(id), ..., nil
Run Code Online (Sandbox Code Playgroud)
我该如何定义自己的方法呢?
- (void)CustomMethod:????? <= want to take infinite arguments {
}
Run Code Online (Sandbox Code Playgroud)
Joe*_*Joe 20
"无限参数"是变量参数,使用它们的方法称为可变参数方法.您可以使用与NSMutableArray示例相同的方式定义它们.Apple的技术问答有一个如何实现它的例子.
- (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);
}
}
Run Code Online (Sandbox Code Playgroud)
nil争论的原因是您知道何时到达列表的末尾.像功能NSLog和printf不需要的最后一个参数是nil因为它可以在格式字符串计数符的数量(%d,%s等...)
| 归档时间: |
|
| 查看次数: |
2278 次 |
| 最近记录: |