gpt4 book ai didi

Objective-C 传递...无终止参数列表

转载 作者:太空狗 更新时间:2023-10-30 03:13:29 24 4
gpt4 key购买 nike

ObjectiveC 中的 ... 有一些问题。

我基本上是在包装一个方法,并想接受一个 nil 终止列表,然后直接将该列表传递给我正在包装的方法。

这是我所拥有的,但它会导致 EXC_BAD_ACCESS 崩溃。检查本地变量,当 otherButtonTitles 只是一个 NSString 时,当它与 otherButtonTitles:@"Foo", nil]

+ (void)showWithTitle:(NSString *)title
message:(NSString *)message
delegate:(id)delegate
cancelButtonTitle:(NSString *)cancelButtonTitle
otherButtonTitles:(NSString *)otherButtonTitles, ...
{
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:title
message:message
delegate:delegate
cancelButtonTitle:cancelButtonTitle
otherButtonTitles:otherButtonTitles] autorelease];
[alert show];
}

我如何简单地从传入参数虹吸到传出参数,同时保留完全相同的 nil 终止列表?

最佳答案

您不能这样做,至少不能以您想要的方式这样做。你想要做什么(传递变量参数)需要在接受 va_listUIAlertView 上有一个初始化器。没有一个。但是,您可以使用 addButtonWithTitle: 方法:

+ (void)showWithTitle:(NSString *)title
message:(NSString *)message
delegate:(id)delegate
cancelButtonTitle:(NSString *)cancelButtonTitle
otherButtonTitles:(NSString *)otherButtonTitles, ...
{
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:title
message:message
delegate:delegate
cancelButtonTitle:cancelButtonTitle
otherButtonTitles:nil] autorelease];
if (otherButtonTitles != nil) {
[alert addButtonWithTitle:otherButtonTitles];
va_list args;
va_start(args, otherButtonTitles);
NSString * title = nil;
while(title = va_arg(args,NSString*)) {
[alert addButtonWithTitle:title];
}
va_end(args);
}

[alert show];
}

当然,这是非常具体的问题。真正的答案是“您不能将变量参数列表隐式传递给没有 va_list 参数的方法/函数”。因此,您必须找到解决问题的方法。在你给出的例子中,你想用你传入的标题制作一个 alertView。幸运的是, UIAlertView 类有一个方法,你可以迭代调用它来添加按钮,从而实现相同的目的整体效果。如果它没有这个方法,那你就不走运了。

另一个非常困惑的选择是让它成为一个可变参数宏。可变参数宏如下所示:

#define SHOW_ALERT(title,msg,del,cancel,other,...) { \
UIAlertView *_alert = [[[UIAlertView alloc] initWithTitle:title message:msg delegate:del cancelButtonTitle:cancel otherButtonTitles:other, ##__VA_ARGS__] autorelease]; \
[_alert show]; \
}

但是,即使使用可变参数宏方法,您每次想要执行此操作时仍然需要一个自定义宏。这不是一个非常可靠的选择。

关于Objective-C 传递...无终止参数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2345196/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com