开发者

Passing NSArray Pointer Rather Than A Pointer To a Specific Type

I've just written a piece of code to display a UIActionSheet within my app. Whils开发者_如何学Pythont looking at the code to initialise my UIActionSheet something struck me as a little strange. The initialisation function has the following signature...

initWithTitle:(NSString *)title delegate:(id UIActionSheetDelegate)delegate cancelButtonTitle:(NSString *)cancelButtonTitle destructiveButtonTitle:(NSString *)destructiveButtonTitle otherButtonTitles:(NSString *)otherButtonTitles

As you can see the otherButtonTitles parameter is a pointer to a String. In my code I set it as follows...

otherButtonTitles: @"Title", @"Date", nil

Although this compiles fine I don't really understand how it works. My reading of the statement is that I have created an inline array containing two elements (Title and Date). How come this then compiles? I'm passing a NSArray* in place of a NSString*. I know from a little of understanding of C++ that an array is really a pointer to the first element. So is this inline array that I'm creating a C array as opposed to a NSArray?

What I'm hoping to achieve is to be able to pass a static NSArray* used elsewhere in my class to the otherButtonTitles parameter. But passing the NSArray* object directly doesn't work.


There's no NSArray involved, and the method signature you quoted is incomplete. The actual signature is

… otherButtonTitles:(NSString *)otherButtonTitles, ...;
//                                               ^^^^^

The , ... indicates variadic function (varargs), which means arbitrarily many arguments may be supplied after otherButtonTitles.

This is a C feature. The called function can receive the arguments using methods in stdarg.h. Since ObjC is a superset of C, varargs is supported for ObjC methods as well, using the , ... as shown.

For example, varargs is also used in +[NSArray arrayWithObjects:] and +[NSString stringWithFormat:] (which may be your confusion that an "array" is passed).


If you have an NSArray, you could insert the buttons after the action sheet is created using -addButtonWithTitle:.

for (NSString* title in array)
   [actionSheet addButtonWithTitle:title];


This is nothing to do with arrays. You are using the basic ANSI C functions for variable arguments. Look up va_list, va_start and va_arg.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜