我正在尝试使用&创建一个采用多个参数的方法(用于地址)。我想做的是让方法做一些计算并调整参数,以便在其他地方使用它们。
我已将方法定义为:
- (void) convertParameters: (double *)x: (double *)y: (double *)z: (double *)height: (double *)width: (double *)phi: (double *)theta: (double *)psi: (int) topLeft: (int) topRight: (int) bottomLeft: (int) bottomRight
{
...
}
我无法弄清楚如何调用该方法。我一直在尝试这个:
double x, y, z, height, width, phi, theta, psi;
[self convertParameters: &x &y &z &height &width &phi &theta &psi topLeft topRight bottomLeft bottomRight];
但是我从Xcode那里得到了这些错误:
错误:二进制&
的操作数无效错误:'topRight'之前的语法错误
错误:二进制&
的操作数无效错误:'topRight'之前的语法错误
之前我已将topRight等定义为: const int topLeft = 25; const int topRight = 29; const int bottomLeft = 17; const int bottomRight = 13; 它们可以在代码中的其他地方使用。我很难过如何解决这个问题。
答案 0 :(得分:6)
你的方法定义搞砸了。您有类型声明但没有实际参数。您似乎将方法名称中的参数名称与实际参数混淆,但它们是分开的。它应该是这样的:
- (void) convertX:(double *)x y:(double *)y z:(double *)z height:(double *)height width:(double *)width phi:(double *)phi theta:(double *)theta psi:(double *)psi topleft:(int)topLeft topRight:(int)topRight bottomLeft:(int)bottomLeft bottomRight:(int)bottomRight
{
...
}
了解如何使用方法名称的“y:
”部分,后跟参数(double *)y
?这就是它的工作原理。您不能将类型放在方法名称的部分上。
您还需要在调用方法时包含该名称。仅仅在方法名称的部分之后命名变量是不够的。所以你称之为:
[self convertX:&x y:&y z:&z height:&height width:&width phi:&phi theta:&theta psi:&psi topLeft:topLeft topRight:topRight bottomLeft:bottomLeft bottomRight:bottomRight]
答案 1 :(得分:5)
在Objective-C中,方法的名称包括参数的所有冒号。由于您尚未命名参数,因此上述方法的签名将为:
convertParameters::::::::::::;
然而,这使用起来相当麻烦(并且难以记住),因此实现方法的一种常用方法是为参数提供解释他们正在做什么的名称。
参数采用以下形式:
[argumentName]: ([argument type])[argumentIdentifier]
每个参数用空格分隔,其中argumentName
后跟冒号用于将参数传递给方法。
命名方法的更好方法是:
- (void)convertParametersWithX: (double*)x
withY: (double*)y
withZ: (double*)z
height: (double*)height
width: (double*)width
phi: (double*)phi
theta: (double*)theta
psi: (double*)psi
topLeft: (int)topLeft
topRight: (int)topRight
bottomLeft: (int)bottomLeft
bottomRight: (int)bottomRight;
然后将调用如下:
[receiver convertParametersWithX: &x
withY: &y
withZ: &z
height: &height
width: &width
phi: &phi
theta: &theta
psi: &psi
topLeft: topLeft
topRight: topRight
bottomLeft: bottomLeft
bottomRight: bottomRight];
这更容易使用,因为参数名称告诉你参数应该是什么,所以这减少了错误顺序传递参数的错误(这将是一个完全不同的方法)。