如何在 Objective-C 中创建可变参数方法
也许这对你们大多数人来说显然很简单,但是您能否举例说明如何在 C 中创建类似的方法(在 Objective-C 中)和函数来创建类似 NSString
的 函数stringWithFormat:
,或NSLog()
。
只是提醒一下:
[NSString stringWithFormat:@"example tekst %i %@ %.2f", 122, @"sth", 3.1415"];
NSLog(@"account ID %i email %@", accountID, email);
我想创建类似于 NSString
的方法 stringWithFormat:
,NSURL - urlWithFormat
。
Maybe this will be obviously simple for most of you, but could you please give an example how to create similar methods (in Objective-C) and functions in C to create functions like NSString
's stringWithFormat:
, or NSLog()
.
Just to remind:
[NSString stringWithFormat:@"example tekst %i %@ %.2f", 122, @"sth", 3.1415"];
NSLog(@"account ID %i email %@", accountID, email);
I'd like to create the similar to NSString
's method stringWithFormat:
, NSURL - urlWithFormat
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
通常,这些被称为“可变函数”(或方法)。
要创建它,只需使用
, ...
结束您的方法声明,如此时您可能希望将其包装在
printf
中类似的功能,因为从头开始实现其中一个功能充其量只是尝试。请注意使用
NSLogv
而不是NSLog
;考虑NSLog(NSString *, ...);
与NSLogv(NSString *, va_list);
,或者如果你想要一个字符串;NSString *
上的initWithFormat:arguments:
。另一方面,如果您不使用字符串,而是使用类似的东西,
事情就会变得容易得多。
在这种情况下,不要使用 vprintf 样式的函数,而是使用遍历 args 的循环,假设 id,然后像在任何循环中一样解析它们。
当然,最后一个示例假设 va_args 列表以 nil 结尾。
注意:为了使这项工作正常进行,您可能必须包含
;但如果没记错的话,它会与 NSLogv 一起包含在内,这意味着它是通过“Foundation.h”下降的,因此也是“AppKit.h”和“Cocoa.h”以及其他一些;所以这应该是开箱即用的。What these are called, generally, is "variadic functions" (or methods, as it were).
To create this, simply end your method declartion with
, ...
, as inAt this point you probably want to wrap it in a
printf
-like function, as implementing one of those from scratch is trying, at best.Note the use of
NSLogv
and notNSLog
; considerNSLog(NSString *, ...);
vsNSLogv(NSString *, va_list);
, or if you want a string;initWithFormat:arguments:
onNSString *
.If, on the other hand, you are not working with strings, but rather something like
things get a lot easier.
In that case, instead of a
vprintf
-style function, use a loop going throughargs
, assuming id as you go, and parse them as you would in any loop.This last sample, of course, assumes that the va_args list is nil-terminated.
Note: In order to make this work you might have to include
<stdarg.h>
; but if memory serves, this gets included in connection with NSLogv, meaning it comes down by way of "Foundation.h", therefore also "AppKit.h" and "Cocoa.h", as well as a number of others; so this should work out of the box.如果要将变量参数传递给 stringWithFormat:,请使用以下内容:
If you want to pass the variable arguments to stringWithFormat:, use something like:
这里需要提到的是,这里的第一个 NSString 参数作为格式,另一个是在变量参数中传递的。正确的?因此,在进入 for 循环之前,您需要处理一个参数。
One thing to mention here is that, the first NSString parameter here comes as format, and the other are passed in the variable argument. right? So before entering the for loop, you have one parameter to handle.
这是 GNUStep 的实现
Here is GNUStep's implementation