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

南笙酒味 提交于 2019-12-04 12:32:16

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];
}

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.

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!