Getting an EXC_BAD_ACCESS with va_list
Following the sample in article http://cocoawithlove.com/2009/05/variable-argument-lists-in-cocoa.html, I've written some custom handling of variable argument methods for forwarding them to another method.
- (void) someMethod:(NSString *)name
wit开发者_如何转开发tParamsAndKeys:(id)firstParam, ... {
va_list args;
va_start(args, firstParam);
NSDictionary* paramsAndKeys =
[[NSDictionary alloc] initWithObjectsAndKeys:firstParam, args, nil];
va_end(args);
}
But I get EXC_BAD_ACCESS. So then I tried removing nil
from arguments to NSDictionary:
NSDictionary* paramsAndKeys =
[[NSDictionary alloc] initWithObjectsAndKeys:firstParam, args];
Again the exception. Now I've got an exception from initWithObjectsAndKeys:
for invalid parameters.
I'm wondering if some way exists for just forwarding variable arguments to another method?
See this question: Variadic list parameter
Generally it is not possible to do that. You have to parse all params and add them to that dictionary:
NSMutableArray* values = [NSMutableArray arrayWithObject: first_param];
NSMutableArray* keys = [NSMutableArray array];
va_list args;
va_start(args, t1);
id arg;
int i = 0;
while ( ( arg = va_arg( args, id) ) != nil ) {
if( (++i)%2 )
[values addObject: arg];
else
[keys addObject: arg];
}
NSDictionary* dict = [NSDictionary dictionaryWithObjects: values forKeys: keys];
I'm wandering if exists some way for just forwarding variable arguments to another method?
No - Passing an ellipsis to another variadic function.
That's why such functions/methods are rare (thanks goodness).
精彩评论