Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining methods with NSString with format

How do you define a method in your own classes that accepts an NSString with format?

I see several different things using it like NSLog, [NSPredicate predicateWithFormat:(NSString *)predicateFormat, ...] and of course [NSString stringWithFormat:(NSString *)format, ...]

Also, in the header files, NSLog and stringWithFormat have the following after their declaration: NS_FORMAT_FUNCTION(1,2). Googling didn't help much with telling me what this meant.

Obviously the ellipsis is the format parameters, but I don't know how to deal with them in the method itself.

like image 231
Dan2552 Avatar asked Jan 16 '23 04:01

Dan2552


1 Answers

You need to make use of some C-code:

- (void)someMethod:(NSString *)format,... {
    va_list argList;
    va_start(argList, format);
    while (format) {
        // do something with format which now has next argument value
        format = va_arg(argList, id);
    }
    va_end(argList);
}

And it's possible to forward the args in to NSString as follows:

- (void)someMethod:(NSString *)format,... {
    va_list args;
    va_start(args, format);
    NSString *msg = [[NSString alloc] initWithFormat:format arguments:args];
    va_end(args);
}
like image 153
rmaddy Avatar answered Jan 25 '23 01:01

rmaddy