Objective C可变参数函数的第一个参数是必需的吗? [英] Is the 1st argument of an Objective C variadic function mandatory?

查看:325
本文介绍了Objective C可变参数函数的第一个参数是必需的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是范例中的可变参数函数Obj C。


$ b

  //这个方法需要一个对象和一个可变数目的参数
- (void)appendObjects:(id)firstObject,...;

将第一个参数作为Obj C对象是否真的是强制性的?如果没有,应该是什么语法?



编辑:感谢您的回应 - 第一个参数不需要是 NSObject ,但我要问的是:是否有可能完全消除第一个参数? 我可能没有在第一次提出问题;对不起,


上面的声明会引发以下错误: Expected';'after method prototype

解决方案

它并不一定是真的。每个Objective-C方法都有两个隐藏的参数, self _cmd (按此顺序)。 self 是不言而喻的(哈哈),但是一个鲜为人知的是 _cmd ,它就是选择器被用来调用当前的方法。这使得使用Objective-C方法的可变参数成为可能,而不需要像使用标准可变参数C函数那样使用初始参数。

   - (void)someMethod:... 
{
va_list va;

va_start(va,_cmd);

//用va_arg处理所有参数

va_end(va);
}

然后你可以调用这样的方法:

  [someObj someMethod:1,2,3]; 


Here is an example of a variadic function in Obj C.

// This method takes an object and a variable number of args
- (void) appendObjects:(id) firstObject, ...;

Is it really mandatory to have the first argument as an Obj C object? If not, what should be the syntax?

EDIT: Thanks for your responses - the first argument does not need to be an NSObject, but what I meant to ask is: Is it possible to do away with the first argument altogether? I probably did not frame the question well the first time around; sorry about that

- (void) appendObjects: ...;

The above declaration throws the following error: Expected ';' after method prototype

解决方案

It doesn't have to be anything really. There are two hidden arguments to every Objective-C method, self, and _cmd (in that order). self is self-explanatory (haha), but a lesser-known one is _cmd, which is simply the selector that was used to invoke the current method. This makes it possible to use variadic arguments with Objective-C methods seemingly without using an initial argument like you do with a standard variadic C function.

- (void) someMethod:...
{
    va_list va;

    va_start(va, _cmd);

    // process all args with va_arg

    va_end(va);
}

Then you can call the method like this:

 [someObj someMethod:1, 2, 3];

这篇关于Objective C可变参数函数的第一个参数是必需的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆