Cocoa - 从另一个可变参数调用可变参数方法(NSString stringWithFormat call) [英] Cocoa - Calling a variadic method from another variadic one (NSString stringWithFormat call)
问题描述
我有一个问题与 [NSString strigWithFormat:format]
因为它返回一个id,我有很多代码,我把NSString var更改为其他个人类型。但编译器不会阻止我有一个NSString将被设置为另一种类型的对象的地方。
I have a problem with [NSString strigWithFormat:format]
because it returns an id, and I have a lot of code where I changed a NSString var to an other personal type. But the compiler does not prevent me that there are places where a NSString is going to be set into another type of object.
所以我写一个类NSString和我打算把 stringWithFormat
的所有调用替换为 myStringWithFormat
。
So I'm writing a category of NSString and I'm goind to replace all my calls to stringWithFormat
to myStringWithFormat
.
代码是:
@interface NSString (NSStringPerso)
+ (NSString*) myStringWithFormat:(NSString *)format;
@end
@implementation NSString (NSStringPerso)
+ (NSString*) myStringWithFormat:(NSString *)format {
return (NSString*)[NSString stringWithFormat:format];
}
@end
编译器告诉我Format not a string没有格式参数。
The compiler tells me that "Format not a string literal and no format arguments".
你看到任何方法使这项工作吗?
Do you see any way to make this work ?
推荐答案
NSString
包括从变参函数接收参数列表的方法。看看这个示例函数:
NSString
includes a method that takes in an argument list from a variadic function. Look at this sample function:
void print (NSString *format, ...) {
va_list arguments;
va_start(arguments, format);
NSString *outout = [[NSString alloc] initWithFormat:format arguments:arguments];
fputs([output UTF8String], stdout);
[output release];
va_end(arguments);
}
一些代码是不相关的,但关键是 NSString * output = [[NSString alloc] initWithformat:format arguments:arguments];
。这是如何在一个可变函数/方法中构造一个 NSString
。
Some of that code is irrelevant, but the key line is NSString *output = [[NSString alloc] initWithformat:format arguments:arguments];
. That's how you can construct an NSString
in a variadic function/method.
在你的case,你的代码应该是这样:
In your case, your code should look something like this:
+ (NSString *)myStringWithFormat:(NSString *)format, ... {
va_list arguments;
va_start(arguments, format);
NSString *formattedString = [[NSString alloc] initWithFormat:format arguments:arguments];
va_end(arguments);
// perform some modifications to formattedString
return [formattedString autorelease];
}
这篇关于Cocoa - 从另一个可变参数调用可变参数方法(NSString stringWithFormat call)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!