Reputation: 1264
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.
Upvotes: 4
Views: 2678
Reputation: 318944
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);
}
Upvotes: 7
Reputation: 40221
You're looking for Objective-C methods with variable number of arguments. Here is how it's done:
Declaration in the header:
- (void)setContentByAppendingStrings:(NSString *)firstString, ...
NS_REQUIRES_NIL_TERMINATION;
Implementation:
- (void)setContentByAppendingStrings:(NSString *)firstArg, ...
{
NSMutableString *newContentString = [NSMutableString string];
va_list args;
va_start(args, firstArg);
for (NSString *arg = firstArg; arg != nil; arg = va_arg(args, NSString*))
{
[newContentString appendString:arg];
}
va_end(args);
contents = newContentString;
}
Source: Cocoa With Love.
Upvotes: 2