How to create a method that takes strings with a format directly as an argument?

I don’t know exactly how to raise this question. I want to create a method like stringWithFormat:or predicateWithFormat:, i.e. My method takes an argument directly as a string with format specifiers. How can I achieve this?

eg.,

-(void) someMethod: (NSString *)str, format; 

So I can later call it the following:

[someObject someMethod:@"String with format %@",anotherString];

This does not apply to any particular context.

I worked predicateWithFormatwith code similar to:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like myName"];

This did not work, but:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like 'myName'"];

worked similarly:

NSString *str = @"myName";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like %@",str];

So this means that the method is able to understand whether the format specifiers used inside them have the given argument. I'm curious how to do this?

+5
source share
2 answers

. :

-(void) someMethod: (NSString *)str, ...; // Yes, three dots

. , , . , stringWithFormat , %.

- (void) someMethod:NSString *)str, ... {
    va_list args;
    va_start(args, str);
    int some_count = /* figure out how many args there are */;
    for( int i = 0; i < some_count; i++ ) {
        value = va_arg(args, <some_type>); // You need to derive the type from the format as well
    }
    va_end(args);
}
+4

varargs va_start, va_end ..:

-(void) someMethod: (NSString *)fmt, ...
{
    va_list va;
    va_start(va, fmt);    
    NSString *string = [[NSString alloc] initWithFormat:fmt
                                              arguments:va];
    va_end(va);

    // Do thing with string
}

, vararg , , printf() [NSString stringWithFormat], , , . , -.

+10

All Articles