2

我试图理解这样的构造:

  - (void)someMethodWithArgs:(type?) param, ...
{
        ???
}

[self someMethodWithArgs:arg1, arg2, arg3];
  • 如何访问参数列表?
  • 例如,“type”应该是指针,还是可以是“int”?
4

3 回答 3

4

Objective-C 函数的工作方式。

宣言

- (void) someMethodWithArgA:(type)paramName argB:(typeB)paramNameB
{
     // do something with paramName and paramNameB 

}

打电话

[self someMethodWithArgA:val argB:valB];

C-等价物是:

void someMethodWithArgs(type paramName, typeB paramNameB)
{
     // do something with paramName and paramNameB    
}

someMethodWithArgs(val,valB);

当然,与 C 一样,变量类型可以是任何东西(为什么它们应该只是指针?)。


一个简单的例子:

- (int)addNum:(int)a withNum:(int)b
{
      int c = a+b;
      return c;
}

int k = [self addNum:2 withNum:3];
// k = 5

参考

面向对象编程的 Objective-C 模型基于向对象实例传递消息。在 Objective-C 中,不是简单地调用一个方法;而是调用一个方法。一发消息

http://en.wikipedia.org/wiki/Objective-C#Messages


更新

实现具有可变数量参数的方法

#import <Cocoa/Cocoa.h>

@interface NSMutableArray (variadicMethodExample)

- (void) appendObjects:(id) firstObject, ...; // This method takes a nil-terminated list of objects.

@end

@implementation NSMutableArray (variadicMethodExample)

- (void) appendObjects:(id) firstObject, ...
{
     id eachObject;
     va_list argumentList;
     if (firstObject) // The first argument isn't part of the varargs list,
     {                                   // so we'll handle it separately.
          [self addObject: firstObject];
          va_start(argumentList, firstObject); 
          // Start scanning for arguments after firstObject.

          // As many times as we can get an argument of type "id"
          while (eachObject = va_arg(argumentList, id)) 
                 [self addObject: eachObject]; 

          va_end(argumentList);
     }
}

@end

来自:http: //developer.apple.com/library/mac/#qa/qa1405/_index.html

于 2012-04-25T08:29:36.803 回答
4

在 ObjC 参数列表语法中源自 C 参数列表语法。

- (void) appendObjects:(id) firstObject, ...
{
id eachObject;
va_list argumentList;
va_start(argumentList, firstObject); // Start scanning for arguments after firstObject.
while (eachObject = va_arg(argumentList, id)) // As many times as we can get an argument of type "id"
  [self addObject: eachObject]; // that isn't nil, add it to self's contents.
va_end(argumentList);
}

您可以从此处找到更多信息:developer.apple.com

更新:哎呀,我有点晚了:)

于 2012-04-25T08:44:27.637 回答
1

Matt Gallagher 提供了一个关于变量参数列表的很好的教程:

Cocoa 中的变量参数列表

在 Apple 的文档中,还有一个关于此主题的简短技术问答 QA1405:

Objective-C 方法中的变量参数

于 2012-04-25T08:42:41.080 回答