Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 返回计算对象_Objective C_Methods - Fatal编程技术网

Objective c 返回计算对象

Objective c 返回计算对象,objective-c,methods,Objective C,Methods,我有一个基本的矩形类。我试图计算右上角的原点、宽度和高度 我在main.m中设置原点、宽度和高度,我可以记录它们并获得正确的值。当我尝试在矩形上调用名为upperRight的矩形方法时,无论输入如何,都会得到0,0 这是我在main中使用的行。m: NSLog(@"The upper right corner is at x=%f and y=%f", myRectangle.upperRight.x, myRectangle.upperRight.y); 下面是与矩形类相关的(我认为): @

我有一个基本的矩形类。我试图计算右上角的原点、宽度和高度

我在main.m中设置原点、宽度和高度,我可以记录它们并获得正确的值。当我尝试在矩形上调用名为upperRight的矩形方法时,无论输入如何,都会得到0,0

这是我在main中使用的行。m:

NSLog(@"The upper right corner is at x=%f and y=%f", myRectangle.upperRight.x, myRectangle.upperRight.y);
下面是与矩形类相关的(我认为):

@implementation Rectangle

{
XYPoint *origin;
XYPoint *originCopy;
XYPoint *upperRight;
}

@synthesize width, height;

-(XYPoint *) upperRight {
upperRight.x = origin.x + width;
upperRight.y = origin.y + height;
return upperRight;
}
即使我尝试在方法中设置upperRight.x=200,我仍然会在main中返回0,0

我显然缺少一些基本的理解

编辑:

以下是设置值的主要内容:

    Rectangle *myRectangle = [[Rectangle alloc]init];
    XYPoint *myPoint = [[XYPoint alloc]init];
    XYPoint *testPoint = [[XYPoint alloc]init];
    //XYPoint *translateAmount = [[XYPoint alloc]init];

    [myRectangle setWidth: 15 andHeight: 10.0];
    [myPoint setX: 4 andY: 3];
下面是XYPoint.m:

#import "XYPoint.h"

@implementation XYPoint

@synthesize x, y;

-(void) setX:(float)xVal andY:(float)yVal {
x = xVal;
y = yVal;
}

@end

假设
XYPoint
CG/NSPoint
相同(一个带有两个
float
struct
),那么为什么要持有指向它们的指针

我想你的意思是:

implementation Rectangle
{
    XYPoint origin;
    XYPoint originCopy;
    XYPoint upperRight;
}

// Strange semantics here... a method that modifies upperRight before returning it?!?
// So why is upperRight an instance variable?  Something is rotten in the state of Denmark.
-(XYPoint) upperRight {
    upperRight.x = origin.x + width;
    upperRight.y = origin.y + height;
    return upperRight;
}

这只是猜测,因为您没有披露
XYPoint
..

以下是我最终所做的符合我最初方法的事情(我不知道它是否理想)


你能告诉我你什么时候做设置/通话吗?我是初学者。返回上角的正确方法是什么?@tangobango您需要保留原点和大小(请参阅NS/CGRect)。然后从origin+size计算右上角,因此不需要将右上角作为实例变量。所以我应该在main中进行此计算?@tangobango如果“make it”是指“calculation it”,那么是的。你需要考虑什么样的变量需要存在,以便你的类工作和什么可以计算。然而,我的回答的要点是,您持有指向
XYPoint
对象的指针,我认为这是不正确的。谢谢。我将提出计算。谢谢你提供我需要的实例变量的信息。我对指针问题没有任何知识可以评论。我正在研究Kochan的Objective-C,他就是这样展示的。如果
XYPoint
是合适的Objective-C对象,我觉得这很不错。
-(XYPoint *) upperRight {
XYPoint *result = [[XYPoint alloc]init];

result.x = origin.x + width;
result.y = origin.y + height;
return result;
}