I don’t know exactly how to put this question.
I want to create a method like stringWithFormat: or predicateWithFormat:, i.e. my method accepts argument directly as a string with format specifiers. How can I achieve this?
E.g.,
-(void) someMethod: (NSString *)str, format;
So that I can later call it like:
[someObject someMethod:@"String with format %@",anotherString];
This is not in relation to any particular context.
I was working predicateWithFormat with a code similar to:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like myName"];
This didn’t work, but:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like 'myName'"];
worked similar to:
NSString *str = @"myName";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like %@",str];
So this means the method is able to understand if the argument given has format specifiers used inside them. I’m curious how can this be done?
You are looking for methods with variable number of parameters. Methods need to be declared like this:
Inside the method you use macros to extract parameters one by one. The first parameter needs to supply enough information to tell how many other parameters are passed. For example,
stringWithFormatcan tell how many parameters are passed by counting unescaped%format specifiers.