开发者

How can I process multiple parameters in a method like NSLog?

This has been asked before, but I dont get my head around this. I开发者_如何学JAVA have my own onscreen Logger and it has a method "append" that should work pretty much as NSLog, taking multiple parameters.

So instead of writing this :

int mynum = 19;
NSLog(@"This is a number %d",mynum);

I want to do this :

[Logger append:@"This is a number %d",mynum];

Any idea how i could do this ?

Thanks


Okay, here's the hard way. :-)

Use the stdarg.h macros to create a va_list copy of your additional arguments, then create a string with that, using the -initWithFormat:arguments: method:

-(void) append:(NSString*)format, ... {
    va_list args, args_copy;
    va_start(args, format);
    va_copy(args_copy, args);
    va_end(args);

    NSString *logString = [[NSString alloc] initWithFormat:format
                                                 arguments:args_copy];
    // Append logString to your logger

    va_end(args_copy);
    [logString release];
}

This way gives you all the flexibility of NSLog() itself, supporting any number and type of arguments.


You want an ellipsis, e.g.

-(SomeResult*)append:(id)object,... {
  id obj;
  va_list argumentList;
  va_start(argumentList, obj); 
  while (obj = va_arg(argumentList, id)) // Do something with obj
  va_end(argumentList);
  // ...
}


[Logger append:[NSString stringWithFormat:@"This is a number %d",mynum]];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜