问题
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.
So I'm writing a category of NSString and I'm goind to replace all my calls to stringWithFormat
to myStringWithFormat
.
The code is :
@interface NSString (NSStringPerso)
+ (NSString*) myStringWithFormat:(NSString *)format;
@end
@implementation NSString (NSStringPerso)
+ (NSString*) myStringWithFormat:(NSString *)format {
return (NSString*)[NSString stringWithFormat:format];
}
@end
The compiler tells me that "Format not a string literal and no format arguments".
Do you see any way to make this work ?
回答1:
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);
}
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.
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];
}
回答2:
No Objective-C expert here, but the original method signature for stringWithFormat
includes ellipses, which allows you to pass in the arguments that are going to be substituted to the placeholders in the format argument
.
EDIT: stringWithFormat
is a so-called variadic method. Here's a link to an example.
回答3:
Thank you for your help. Reading your reference documentations, I found the solution !
This works :
In the .h
@interface NSString (NSStringPerso)
+ (NSString*) strWithFormatPerso:(id)firstObject, ...;
@end
In the .m
@implementation NSString (NSStringPerso)
+ (NSString*) strWithFormatPerso:(id)firstObject, ... {
NSString* a;
va_list vl;
va_start(vl, firstObject);
a = [[[NSString alloc] initWithFormat:firstObject, vl] autorelease];
va_end(vl);
return a;
}
@end
来源:https://stackoverflow.com/questions/4702871/cocoa-calling-a-variadic-method-from-another-variadic-one-nsstring-stringwith