Objective C 可变参数函数的第一个参数是强制性的吗?
下面是 Obj C 中可变参数函数的示例。
// This method takes an object and a variable number of args
- (void) appendObjects:(id) firstObject, ...;
第一个参数必须作为 Obj C 对象吗?如果不是,语法应该是什么?
编辑:感谢您的回复 - 第一个参数不需要是 NSObject
,但我想问的是:是否可以完全取消第一个参数? strong> 我第一次可能没有很好地提出这个问题;对此感到抱歉
- (void) appendObjects: ...;
上面的声明抛出以下错误:预期';'方法原型之后
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它不一定是真的。每个 Objective-C 方法都有两个隐藏参数,
self
和_cmd
(按顺序)。self
是不言自明的(哈哈),但一个不太为人所知的是_cmd
,它只是用于调用当前方法的选择器。这使得在 Objective-C 方法中使用可变参数成为可能,而无需像使用标准可变参数 C 函数那样使用初始参数。然后你可以像这样调用该方法:
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.Then you can call the method like this:
Objective-C 实现可变参数的方法与标准 C 中的相同。因此您可以传入非 Objective-C 对象参数。
就我个人而言,我会使用第一个非隐藏参数来传递以下可变参数列表的长度(对于非 Objective-C 对象 - 否则我会使用 nil 终止)
The Objective-C way to implement variadic args is the same as in standard C. So you can pass in non-Objective-C object arguments.
Personally I'd use the first non-hidden arg to pass in the length of the following variadic list (for non-Objective-C objects - otherwise I'd use nil-termination)
不,它不一定是一个对象。您可以编写一个采用浮点数的可变参数函数,例如:
No, it doesn’t have to be an object. You can write a variadic function taking floats, for example: