سؤال

I am in Objective-C trying to create a custom Variadic logging function, specifically I would like to "rebuild" string formats like what you send to NSLog. I have tried to understand Variadic functions but the language used to describe the different aspects are over my head, and all of the examples I have found are about summing a bunch of integers and not rebuilding string formats.

An overly simple example of what I am trying to do would look like is this:

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

That is to say I want to bring a typical string format into the function and rebuild that format as a string inside of the function.

Like I said this is an overly simple example, there would be more going on than simply sending it back out again and thus there are other reasons for me wanting to do this. Those reasons aside: How do I rebuild a string format inside of a Variadic function?

UPDATE:

Currently I am using the following code:

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

Currently this works but the call (last line above) is fairly unreadable. I would like to make the call like this:

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

Technically speaking my current code works fine, the reason I would like to make this change is because the second way is SO much more readable! A line that starts "MyLog(..." is much more readable than "[self output:[NSString stringWithFormat:..."

هل كانت مفيدة؟

المحلول

You can do this:

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

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

And call it like you want:

myLog(@"You started out with %i tabs and I deleted %i (%i%%) of them.\n", totalTabs, deletedTabs, totalTabs ? 100*deletedTabs/totalTabs : 0]);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top