by mikeash · 13y ago · 0 comments
- (NSString *)format: ...;
It would be oh-so convenient, meaning you could write formatting operations like this: newstr = [@"%d %@ %s" format: 42, @"blah", "yep"];
Given the constraints we have to work with, I'd say your best bet would be to simply write a function: newstr = fmt(@"%d %@ %s", 42, @"blah", "yep"); - (NSString *)format:(id)first, ... {
NSUInteger argCount = 0;
BOOL prevPercent = NO;
for (NSUInteger i = 0; i < [self length]; ++i) {
unichar c = [self characterAtIndex:i];
if (prevPercent && c != '%')
++argCount;
prevPercent = c == '%';
}
NSMutableArray *argArr = [NSMutableArray new];
va_list args;
va_start(args, first);
for (NSUInteger i = 0; i < argCount; ++i)
[argArr addObject:va_arg(args, id)];
va_end(args);
switch (argCount) {
case 0: return [NSString stringWithFormat:self, first];
case 1: return [NSString stringWithFormat:self, first, argArr[0]];
case 2: return [NSString stringWithFormat:self, first, argArr[0], argArr[1]];
// ...
}
}
Only supports NSObject arguments, obviously. If you actually wanted to do this approach you'd want to do a better job of parsing the format string and use a more cleverer way of storing the args.Or, for the completely insane approach that probably doesn't actually work (on top of being entirely unportable):
- (NSString *)format:(id)first, ... {
NSUInteger argCount = ...;
va_list args;
va_start(args, first);
void *argList = malloc(sizeof(id) * (argCount + 1));
memcpy(argList, (void*)&first, sizeof(id));
memcpy(argList + sizeof(id), &va_arg(args, void *), sizeof(id) * argCount);
va_end(args);
NSString *ret = [[NSString alloc] initWithFormat:self arguments:argList];
free(argList);
return ret;
} + (id)stringWithFormat:(NSString *)format, ...;
This of course already exists, but if you wanted to do a Rubyfied version of it, then just follow the same general pattern.The reality is, that NSString needs native formatting sugar. Anything else would really just be a hack. I'm not particularly even happy with the [@"Hello ":@"World] syntax, either.
NSString *newS = @"blah " + @(42) + @"!"; newstr = [@"%d %@" format 42, @"blah"];
Implement it as a method that takes a dummy parameter, plus a macro: - (NSString *)format:(int)dummy, ...
#define format format:0,
Awful way to do it, but the resulting syntax is not entirely terrible.