views:

30

answers:

2

Similar to how NSLog takes variable argument list, I want to create my own method.

I have my method declared like this but when I try to access the 'args' variable, I get an EXEC_BAD_ACCESS. What is that I'm not doing correctly here?

- (void)info:(NSString *)formatString, ...
{   
    va_list args;
    va_start(args, formatString);

    NSLog(@"formatString value: %@", formatString);

    // The following line causes the EXEC_BAD_ACCESS
    NSLog(@"args value: %@", args);

    // This is what I'm trying to do:
    NSLog(formatString, args);

    va_end(args);               
}

I was following the 'va_list in Cocoa' section from this blog: http://cocoawithlove.com/2009/05/variable-argument-lists-in-cocoa.html

+1  A: 

There are a couple of mistakes in your code. Firstly, args cannot be printed directly as is. It is a reference to several arguments, and trying to print it using NSLog("%@") will not work. What you can do is use NSLogv() to print it (e.g. NSLogv(format, args);) instead.

Or you can do what I do, and use this function:

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

    fputs([[[[NSString alloc] initWithFormat:format arguments:args] autorelease] UTF8String], stdout);

    va_end(args);
}
itaiferber
thanks - I didn't realize that NSLogv is what should be used.
Justin Galzic
+1  A: 

The "%@" format directive takes an argument, interprets it as an Objective-C object and sends it the "description" selector. That needs to return a NSString which is printed.

So you code is trying to execute ‘[args description]‘, but args is not a Objective-C object, it's of type ‘va_list‘. Hence the exception.

See your link, the implementation of "setContentByAppendingStrings:" shows how do get the arguments out of your va_list.

DarkDust