padam thapa
padam thapa

Reputation: 1477

passing string formatter as argument

I have a function called showMessage which displays the alert message dialog. This function takes string as parameter and shows this string as a message of dialog. At start I wanted the way to pass string and also sting formatter along with it, something like this:

[self showMessageDialog:@"Hello %@", self.studentName];

As you can see what I want to achieve. So I made my function signature something like this:

- (void) showMessageDialog:(NSString *)message, ...{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" 
                                                message:message 
                                               delegate:nil 
                                      cancelButtonTitle:@"OK"
                                      otherButtonTitles:nil];
[alert show];
[alert release];
}

With this I can pass multiple formatters(i mean argument which will go on placeholders) during function call, but I am missing something which doesn't allow me to show my formatter arguments on message. I mean I always get this message on message dialog: "Hello %@".

I know I have missed something like I have made the way to pass the multiple arguments to function call but I think i haven't made it how to place those arguments on their placeholders.

Note: I want to make function work like NSLog, way we call NSLog and pass arguments.

Upvotes: 0

Views: 100

Answers (1)

sergio
sergio

Reputation: 69047

What you are trying to do is building a vararg function. Have a look at this tutorial on how to do it.

Specifically, as far as I understand you will be also be interested in how you can pass your variable argument list from your method to another function taking a variable argument list (say that you want to call sprintf from your showMessageDialog:). This is explained here. Actually, this is easily done (e.g., with NSLog):

- (void) showMessageDialog:(NSString *)message, ... {

    va_list argp;

    va_start(argp, msg);
    NSLog(msg, argp);
    va_end(argp);

}

Upvotes: 1

Related Questions