How do I get a formatted NSString from format and va_list?

时光毁灭记忆、已成空白 提交于 2019-11-30 23:43:05

问题


I'm developing a static library that will be distributed to other developers, who may need debug statements. So I have several levels of logging.

In order to avoid constant appearance of

if(loggingLevelCurrentlySet >= loggingLevelWantedForThisInstance){ 
     NSLog(@"log this");
}

I created a set of logging function wrappers. A simplified version looks like this:

void myLog(int logLevel, NSString *format, va_list args){
    if((loggingLevelCurrentlySet >= logLevel)){
        NSLogv(format, args);
    }
}

void myLogLevel1(NSString *format, ...){
    va_list args;
    va_start(args, format);

    myLog(1, format, args);
    va_end(args);
}

void myLogLevel2(NSString *format, ...){
    va_list args;
    va_start(args, format);

    myLog(2, format, args);
    va_end(args);
}

etc.

But now, I want, from within myLog, access to the fully formated string to do something else with.

void myLog(int logLevel, NSString *format, va_list args){
        NSString *fullString = [NSString stringWithFormat:format, args]; //crashes when args is anything but an empty list
        CFStringRef cfsr = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, format, args);  //also crashes

        //want to use the string here

        if((loggingLevelCurrentlySet >= logLevel)){
            NSLogv(format, args);
        }
}

回答1:


NSString *fullString = [[[NSString alloc] initWithFormat:format arguments:args] autorelease];

There is a method for that ;)

Although I suggest not to use functions, but some simple macro definitions:

#define myLogLevel1(format, ...) myLog(1, format, __VA_ARGS__)
#define myLogLevel2(format, ...) myLog(2, format, __VA_ARGS__)


来源:https://stackoverflow.com/questions/3843573/how-do-i-get-a-formatted-nsstring-from-format-and-va-list

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