为什么UIActionSheet init方法接受字符串数组而不是NSString

时间:2011-07-27 10:18:28

标签: objective-c nsstring nsarray

这确实是一个新手问题,但它可以帮助我更好地理解Objective-c的工作原理。我在iOS应用程序中使用了UIActionSheet。查看文档,这是相关的init方法:

- (id)initWithTitle:(NSString *)title delegate:(id < UIActionSheetDelegate >)delegate cancelButtonTitle:(NSString *)cancelButtonTitle destructiveButtonTitle:(NSString *)destructiveButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ...

whereButtonTitles据说是以逗号分隔的NSString列表。在我看来,这与NSArray相对应,所以我试图引发崩溃:

NSArray *buttons = [NSArray arrayWithObjects:@"B1",@"B2",nil];
UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"Actions" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Delete" otherButtonTitles:buttons];

然后显然应用程序因按钮NSArray而崩溃。 这听起来与Java varargs类似,在类中你可以有类似的东西:

public void myMethod(String... param) {...};

对此方法的合法调用是:

myClass.myMethod("x");
myClass.myMethod("x","Y");

我的iOS应用程序中有很多使用NSArray的方法:

[myClass myMethod:[NSArray arrayWithObjects:....]];

对于我来说,避免分配NSArray,而是传递逗号分隔的NSString列表将非常方便。我怎样才能做到这一点 ?我的意思是,从myMethod的角度来看,接收了什么类型的参数以及如何考虑它?例如,我如何循环通过NSString ???

感谢

2 个答案:

答案 0 :(得分:1)

根据您的示例,以下内容应该有效:

UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"Actions" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Delete" otherButtonTitles:@"B1",@"B2",nil];

它并不比听起来更复杂。 “以逗号分隔的NSString列表”只不过是一个由逗号分隔的NSStrings列表。

答案 1 :(得分:-1)

作为Objective-c的新手,我和我一样,对我来说有点误会。正如格雷厄姆所指出的那样,该方法确实使用了可变参数。乍一看,我完全忽略了这一点,Java varargs符号在Objective-c中具有相同的含义:

public void myMethod(String... var);
-(void)myMethod:(NSString*)var,...;

事实上,如果您看一下UIActionSheet方法签名,它会在部分中使用与其他按钮完全相同的三点符号:

otherButtonTitles:(NSString *)otherButtonTitles, ...

另外,为了处理objective-c中的变量参数,我发现了一个非常有用的链接:

http://cocoawithlove.com/2009/05/variable-argument-lists-in-cocoa.html

提出我的问题,我可以通过实施'三点符号'安全地重写我的所有方法,并丢弃所有不必要的NSArray。