this is really a newbie question, but it would help me to have a better understanding of how Objective-c works. I have made use of UIActionSheet in a iOS app. Looking at documentation this is the relevant init method:
- (id)initWithTitle:(NSString *)title delegate:(id < UIActionSheetDelegate >)delegate cancelButtonTitle:(NSString *)cancelButtonTitle destructiveButtonTitle:(NSString *)destructiveButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ...
Where otherButtonTitles is said to be a comma separated list of NSString. In my mind this is correspondent to an NSArray, so with the intent of caushing a crash I tried:
NSArray *buttons = [NSArray arrayWithObjects:@"B1",@"B2",nil];
UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"Actions" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Delete" otherButtonTitles:buttons];
And then obviously the application crashed because of buttons NSArray. This sounds so similiar to Java varargs, where in a class you can have something like:
public void myMethod(String... param) {...};
A legal call to this method is:
myClass.myMethod("x");
myClass.myMethod("x","Y");
I have a lot of methods in my iOS apps that made us开发者_如何学JAVAe of NSArray:
[myClass myMethod:[NSArray arrayWithObjects:....]];
And it would be very convenient for me to avoid alloc of NSArray but rather passing a comma separated list of NSString. How can I do that ? I mean, from the myMethod point of view, what type of param is received and how should it be considered ? For example how can I cycle trough an NSString ???
thanks
Given your example, the following should work:
UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"Actions" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Delete" otherButtonTitles:@"B1",@"B2",nil];
It's no more complicated than it sounds. A "comma-separated list of NSString" is nothing more than a list of NSStrings, separated by commas.
As the king of Objective-c newbie as I am, here comes a little misundertanding for me. As pointed out by Graham, the method made indeed use of variable arguments. At first glance I completely missing this, the Java varargs notation has this equivalent in Objective-c:
public void myMethod(String... var);
-(void)myMethod:(NSString*)var,...;
Infact if you take a look at UIActionSheet method signature it put exactly the same three dot notation in the part regarding other buttons:
otherButtonTitles:(NSString *)otherButtonTitles, ...
Also for dealing with variable arguments in objective-c I found a very useful link:
http://cocoawithlove.com/2009/05/variable-argument-lists-in-cocoa.html
Coming to my question, I can safely rewrite all my methods by implementing the 'three dot notation', and throw away all the unnecessary NSArray.
精彩评论