Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cocoa - Calling a variadic method from another variadic one (NSString stringWithFormat call)

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 ?

like image 729
Oliver Avatar asked Aug 28 '26 18:08

Oliver


2 Answers

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];
}
like image 83
Itai Ferber Avatar answered Aug 31 '26 11:08

Itai Ferber


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.

like image 37
s.m. Avatar answered Aug 31 '26 10:08

s.m.