In my attempts to understand what I can and cannot do with va_list in (Objective-) C, I came across this little mystery. I was hoping to create a category on NSString
that in some cases will simplify the stringWithFormat:
message, just for fun. What I was aiming for was able to use the implementation as follows:
[@"My %@ format %@!" formattedWith:@"super", @"rocks"];
We hope that the line with the inscription " My super format rocks!
" My super format rocks!
. My (incorrect) implementation of the method is as follows:
- (NSString *)formattedWith:(NSString *)arguments, ... { va_list list; va_start(list, arguments); NSString *formatted = [[[NSString alloc] initWithFormat:self arguments:list] autorelease]; va_end(list); return formatted; }
Now the problem is that as soon as va_start()
is called, va_list is "shortened" (due to the lack of a better word) and contains only the rest of the arguments (in the case of just an example, @"rocks"
remains, plus the calling object that I'm not interested in) . Thus, the message passed to the initWithFormat:
message does the wrong result.
To the question. Are there any ways to change va_list before passing it to the initWithFormat:
message so that I can somehow transfer the first argument back to the list?
I'm not looking for an iterative process, when I scroll through va_list myself, I'm looking to understand the limits of va_list in general. Thanks!
source share