Reputation: 132
Is it possible to do that this way:
- (void) setList:(id) firstObj,...
{
va_list args;
va_start(args,firstObj);
list = [[NSArray alloc] initWithObjects:args]; // Compile error
va_end(args);
}
Upvotes: 3
Views: 1849
Reputation:
Try this:
- (void) setList:(id)firstObj, ... NS_REQUIRES_NIL_TERMINATION
{
va_list args;
va_start(args, firstObj);
list = [[NSMutableArray alloc] initWithObjects:firstObj, nil];
id obj;
while ((obj = va_arg(args, id)) != nil) {
[list addObject:obj];
}
va_end(args);
}
Upvotes: 7
Reputation: 7275
Pretty close, something like this should work. The problem is that there isn't an API function for this, so you have to get the objects out of the list and add them to an array your instantiate.
-(void *)setList:(id)firstObj, ... {
//The array you're holding everything in
arr = [NSMutableArray array];
[arr addObject:firstObject];
//Get the variable list
va_list args;
va_start(args, action1);
//Create the object
id object = va_arg(args, id);
//Keep adding objects until you run out
while(object) {
[arr addObject:object];
object = va_arg(args, id);
}
va_end(args);
}
Upvotes: 2
Reputation: 57179
NSArray
does not have a constructor that takes a va_list
so you will have to loop over the args yourself and add them to a mutable array. You should also add a constraint for the arguments to be nil
terminated.
- (void) setList:(id) firstObj,... __attribute__((sentinel)) //make sure it is nil terminated
{
//You have to add the first object yourself
NSMutableArray *tmplist = [NSMutableArray arrayWithObject:firstObj];
va_list args;
va_start(args,firstObj);
id arg;
while((arg = va_arg(args, id)) != nil)
[tmplist addObject:arg];
va_end(args);
list = [tmplist copy];
}
Upvotes: 5