代码之家  ›  专栏  ›  技术社区  ›  mmccomb

传递nsarray指针而不是指向特定类型的指针

  •  0
  • mmccomb  · 技术社区  · 15 年前

    我刚刚写了一段代码来在我的应用程序中显示uiactionsheet。在查看初始化uiactionsheet的代码时,我觉得有点奇怪。初始化功能具有以下签名…

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

    如您所见,otherButtonTitles参数是指向字符串的指针。在我的代码中,我设置如下…

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

    虽然这本书很好,但我不太明白它是如何工作的。我对语句的理解是,我已经创建了一个包含两个元素(标题和日期)的内联数组。这是怎么编译的?我要传递一个nsarray*来代替nsstring*。从对C++的一点理解中,我知道数组实际上是指向第一个元素的指针。那么,我创建的这个内联数组是C数组,而不是NSarray吗?

    我希望能够将类中其他地方使用的静态nsarray*传递给OtherButtonTitles参数。但是直接传递nsarray*对象不起作用。

    2 回复  |  直到 15 年前
        1
  •  4
  •   kennytm    15 年前

    不涉及NSARRAY,您引用的方法签名不完整。实际签名是

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

    这个 , ... 指示 variadic function (varargs) ,这意味着在 otherButtonTitles .

    这是一个C特性。被调用函数可以使用中的方法接收参数 stdarg.h . 由于objc是c的超集,因此objc方法也支持varargs,使用 ,… 如图所示。

    例如,varargs也用于 +[NSArray arrayWithObjects:] +[NSString stringWithFormat:] (这可能是您对传递“array”的混淆)。


    如果您有一个NSarray,可以在创建操作表后使用 -addButtonWithTitle: .

    for (NSString* title in array)
       [actionSheet addButtonWithTitle:title];
    
        2
  •  1
  •   Paul Lynch    15 年前

    这与数组无关。变量参数使用的是基本的ansi c c函数。仰望 va_list , va_start va_arg .