I have an designated initializer with optional arguments (similar to the following code), and I want to create an autorelease method by calling it. Is there any way to do this?
@interface MyObject : NSObject
- (id)initWithArgs:(id)firstArg, ...;
+ (id)objectWithArgs:(id)firstArg, ...;
@end
@implementation MyObject
- (id)initWithArgs:(id)firstArg, ...
{
if (!firstArg || ![super init]) {
return nil
}
va_list argList;
va_start(argList, firstArg);
id currentObject = firstArg;
do {
NSLog(@"%@", currentObject);
} while ((currentObject = va_arg(argList, id)) != nil);
va_end(argList);
return self;
}
+ (id)objectWithArgs:(id)firstArg, ...
{
// return [[[MyObject alloc] initWithArgs:firstArg, ...] autorelease];
}
@end
You can’t do it. See the comp.lang.c FAQ. The closest thing you can do is to create two versions of your functions, one which takes varargs (
...), and one which takes ava_list. The varargs version can then pass off the work to theva_listversion to avoid duplicate code: