我正在尝试创建一个方法,使用&(对于地址)来获取几个参数.我想做的是让方法做一些计算并调整参数,以便它们可以在别处使用.
我已经将方法定义为:
- (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
{
...
}
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚的是如何调用该方法.我一直在尝试这个:
double x, y, z, height, width, phi, theta, psi;
[self convertParameters: &x &y &z &height &width &phi &theta &psi topLeft topRight bottomLeft bottomRight];
Run Code Online (Sandbox Code Playgroud)
但是我从Xcode那里得到了这些错误:
错误:无效操作数到二进制&
错误:'topRight'之前的语法错误
错误:无效操作数到二进制&
错误:'topRight'之前的语法错误
之前我已经将topRight等定义为:const int topLeft = 25; const int topRight = 29; const int bottomLeft = 17; const int bottomRight = 13; 它们可以在代码中的其他地方使用.我很难过如何解决这个问题.
你的方法定义搞砸了.您有类型声明但没有实际参数.您似乎将方法名称中的参数名称与实际参数混淆,但它们是分开的.它应该是这样的:
- (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
{
...
}
Run Code Online (Sandbox Code Playgroud)
看看你如何拥有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]
Run Code Online (Sandbox Code Playgroud)
在Objective-C中,方法的名称包括参数的所有冒号.由于您尚未命名参数,因此上述方法的签名将为:
convertParameters::::::::::::;
Run Code Online (Sandbox Code Playgroud)
但是,这使用起来相当麻烦(并且难以记住),因此实现方法的一种常用方法是为参数提供解释他们正在做什么的名称.
参数采用以下形式:
[argumentName]: ([argument type])[argumentIdentifier]
Run Code Online (Sandbox Code Playgroud)
每个参数用空格分隔,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;
Run Code Online (Sandbox Code Playgroud)
然后将调用如下:
[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];
Run Code Online (Sandbox Code Playgroud)
这更容易使用,因为参数名称告诉你参数应该是什么,所以这减少了错误顺序传递参数的错误(这将是一个完全不同的方法).
| 归档时间: |
|
| 查看次数: |
1392 次 |
| 最近记录: |