gpt4 book ai didi

iphone - 参数列表语法

转载 作者:行者123 更新时间:2023-12-03 16:24:20 29 4
gpt4 key购买 nike

我试图理解这样的构造:

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

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

最佳答案

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
<小时/>

引用

The Objective-C model of object-oriented programming is based on message passing to object instances. In Objective-C one does not simply call a method; one sends a message.

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

关于iphone - 参数列表语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10311967/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com