我有一个带有可选参数的指定初始值设定项(类似于下面的代码),我想通过调用它来创建一个autorelease方法有办法吗?
@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
最佳答案
你不能这么做。请参见comp.lang.c FAQ。最接近的方法是创建两个版本的函数,一个使用varargs(...
),另一个使用va_list
然后,varargs版本可以将工作传递给va_list
版本,以避免重复代码:
@interface MyObject : NSObject
- (id)initWithArgs:(id)firstArg, ...;
- (id)init:(id)firstArg withVaList:(va_list)args;
+ (id)objectWithArgs:(id)firstArg, ...;
+ (id)object:(id)firstArg withVaList:(va_list)args;
@end
@implementation MyObject
- (id)initWithArgs:(id)firstArg, ...
{
va_list args;
va_start(args, firstArg);
id result = [self init:firstArg withVaList:args];
va_end(args);
return result;
}
- (id)init:(id)firstArg withVaList:(va_list)args
{
// do actual init here:
while((id arg = va_arg(args, id)))
{
// ...
}
}
+ (id)objectWithArgs:(id)firstArg, ...
{
va_list args;
va_start(args, firstArg);
id result = [MyObject object:firstArg withVaList:args];
va_end(args);
return result;
}
+ (id)object:(id)firstArg withVaList:(va_list)args
{
return [[[MyObject alloc] init:firstArg withVaList:args] autorelease];
}
@end
关于c - 如何将可选参数发送到另一个函数/方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1185177/