如何“传递”一个可变数量的参数NSString的+ stringWithFormat: [英] How to "pass on" a variable number of arguments to NSString's +stringWithFormat:

查看:733
本文介绍了如何“传递”一个可变数量的参数NSString的+ stringWithFormat:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Objective-C中编写一个函数,如下面的一个函数,它接受可变数量的参数,并将这些参数传递给 + stringWithFormat: 。我知道 vsnprintf ,但这将意味着将NSString'format'转换为C和回来(也将意味着转换其中的格式化占位符...)。

I would like to write a function in Objective-C such as the one below, that takes a variable number of arguments, and passes those arguments on to +stringWithFormat:. I know about vsnprintf, but that would imply converting the NSString 'format' to C and back (and would also mean converting the formatting placeholders within it as well...).

下面的代码编译,但当然不会像我想要的那样:)

The code below compiles, but of course does not behave as I want :)

NSString *estr(NSString *format, ...) {
    va_list args;
    va_start(args, format);
    NSString *s = [NSString stringWithFormat:format, args];
    va_end(args);
    return s;
}

基本上是: va_list -friendly版本的 + stringWithFormat:方法,还是可以写一个?

Basically: is there a va_list-friendly version of the +stringWithFormat: method, or is it possible to write one?

推荐答案

initWithFormat:arguments:

NSString *estr(NSString *format, ...) {
    va_list args;
    va_start(args, format);
    NSString *s = [[[NSString alloc] initWithFormat:format arguments:args] autorelease];
    va_end(args);
    return s;
}

它们似乎没有方便的构造函数stringWith ...版本

they don't seem to have a convenience constructor "stringWith..." version

这篇关于如何“传递”一个可变数量的参数NSString的+ stringWithFormat:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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