开发者

Arguments after variadic arguments

Objective-C, or Cocoa specifically, supports variadic arguments, like for example class the method on NSString +(NSString *)stringWithFormat:(NSString *)string, .....

Now, what I would like to know is if it is possible to follow that variadic argument must be at the end of the method, or can the method continue after that?

As an example, suppose I have the variadic method (with the appropriate macro),

- (void)setObjects:(id)obj, ... NS_REQUIRES_NIL_TERMINATION;

If I want to use it at a specific index开发者_StackOverflow社区, could I do something like this,

- (void)setObjects:(id)obj, ... NS_REQUIRES_NIL_TERMINATION atIndex:(int)index;

I've been trying, and this specific example doesn't work, giving me an error message saying "Expected ';' after method prototype". Of course, I could shuffle the arguments around to make sure the variadic one is at the end, like this,

- (void)atIndex:(int)index setObjects:(id)obj, ... NS_REQUIRES_NIL_TERMINATION;

This certainly works, but to me it feels rather alien amidst the Cocoa naming conventions -- which is a problem for me.

Thank you,


Variadic arguments must be the last argument. This is because a method in Objective-C is really just an ordinary C function in disguise, and C doesn't allow any arguments after a variadic argument either.

The reason C doesn't allow it has to do with the calling convention that C supports. When you call a variadic function, the number of variadic arguments is not actually known be the function at first. Different functions can then figure it out in different ways. In Objective C, terminating a variadic argument with nil is common. The printf function figures out how many arguments it's passed based on the format string. Since the function doesn't initially know how many variadic arguments there are, it has no way of knowing the memory location of an argument after the variadic argument list.

Look up "C calling conventions" if you wish to know more.

(Some consider this limitation to be a "wart" of the C language, which is fair. However, we are stuck with it due to the need for ABI compatibility. C++ has the same issue with variadic functions.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜