0

我在 Objective-C 中尝试创建自定义 Variadic 日志记录函数,特别是我想“重建”字符串格式,例如您发送到 NSLog 的内容。我试图理解可变参数函数,但用于描述不同方面的语言在我的脑海中,我发现的所有示例都是关于对一堆整数求和而不是重建字符串格式。

我正在尝试做的一个过于简单的示例如下所示:

(void) myLog (NSString*string,...) {
    NSLog(string,...);
}

也就是说,我想将典型的字符串格式带入函数中,并将该格式重建为函数内部的字符串。

就像我说的那样,这是一个过于简单的例子,除了简单地再次将其发送回去之外,还有更多的事情要做,因此我想要这样做还有其他原因。除了这些原因:如何在 Variadic 函数中重建字符串格式?

更新:

目前我正在使用以下代码:

- (void) output:(NSString*)string {
    [_outputStorage appendAttributedString:[[NSAttributedString alloc] initWithString:string attributes:[NSDictionary dictionaryWithObject:[NSFont boldSystemFontOfSize:[NSFont smallSystemFontSize]] forKey:NSFontAttributeName]]];
    DDLogVerbose(@"%@", string);
}
...
[self output:[NSString stringWithFormat:@"You started out with %i tabs and I deleted %i (%i%%) of them.\n", totalTabs, deletedTabs, totalTabs ? 100*deletedTabs/totalTabs : 0]];

目前这可行,但调用(上面的最后一行)相当不可读。我想这样打电话:

myLog(@"You started out with %i tabs and I deleted %i (%i%%) of them.\n", totalTabs, deletedTabs, totalTabs ? 100*deletedTabs/totalTabs : 0]);

从技术上讲,我当前的代码工作正常,我想进行此更改的原因是因为第二种方式更具可读性!以 "MyLog(..." 开头的行比 "[self output:[NSString stringWithFormat:..." 更具可读性

4

1 回答 1

1

你可以这样做:

(void)myLog(NSString *format, ...) {
    va_list args;
    va_start(args, format);
    NSString *msg = [[NSString alloc] initWithFormat:format arguments:args];
    va_end(args);

    NSLog(@"%@", msg);
}

并随心所欲地调用它:

myLog(@"You started out with %i tabs and I deleted %i (%i%%) of them.\n", totalTabs, deletedTabs, totalTabs ? 100*deletedTabs/totalTabs : 0]);
于 2013-07-20T03:24:17.980 回答