0

I referred this SO Answer for creating variadic function in objective C. I tested your code by passing arguments like below:

[self logMessage:@"string: %@\n number: %@\n image: %@",
 @"asdf",
 [NSNumber numberWithInt:23],
 [UIImage imageNamed:@"local.png"]];

and edited the code with NSLog();

- (void)logMessage:(NSString *)format, ... {

    va_list args;
    va_start(args, format);

    id arg = nil;
    int i = 1;
    NSLogv(format, args);
    while ((arg = va_arg(args,NSString *))) {

        NSLog(@"val: %d", i++);
        /// Do your thing with arg here
        //NSString *name = NSStringFromClass([arg class]);
        //NSLog(@"string: %@", name);
    }        
    va_end(args);
}

But the output as follows:

2012-09-28 19:34:45.271 SIMO[2384:c07] string: asdf
 number: 23
 image: <UIImage: 0x8151f80>
2012-09-28 19:34:45.273 SIMO[2384:c07] val: 1
2012-09-28 19:34:45.273 SIMO[2384:c07] val: 2
2012-09-28 19:34:45.274 SIMO[2384:c07] val: 3
2012-09-28 19:34:45.274 SIMO[2384:c07] val: 4
2012-09-28 19:34:45.274 SIMO[2384:c07] val: 5
2012-09-28 19:34:45.275 SIMO[2384:c07] val: 6
2012-09-28 19:34:45.275 SIMO[2384:c07] val: 7
2012-09-28 19:34:45.276 SIMO[2384:c07] val: 8

This tells that the argument is 8, but I passed only 3 (NSString, NSNumber, UIImage) I can't get the concept.. Could you clarify me Could anyone clarify this

1 Answer 1

2

va_arg doesn't really know when the argument list ends. The approach you're using expects the argument list to be terminated by nil, like +[NSArray arrayWithObjects:].

So either change your invocation to add nil at the end of the argument list, or find some other way of knowing when the arguments are over (e.g. for a printf clone, you might know the number of format arguments from the format string itself).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.