如何从格式和va_list获取格式化的NSString? [英] How do I get a formatted NSString from format and va_list?

查看:126
本文介绍了如何从格式和va_list获取格式化的NSString?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个静态库,该库将分发给可能需要调试语句的其他开发人员。所以我有几个级别的日志记录。

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.

为了避免不断出现

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

等。

但是现在,我希望从myLog中访问完全格式化的字符串以执行其他操作。

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


推荐答案

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

有一种方法;)

虽然我建议不使用函数,但是一些简单的宏定义:

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__)

这篇关于如何从格式和va_list获取格式化的NSString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆