对象被返回值改变?

Object being changed by returning value?

这是非常基本的,但我不明白为什么我这样做:

int main(int argc, const char * argv[]) {
@autoreleasepool {
    Rectangle *myRect = [[Rectangle alloc] init];
    XYPoint *myPoint = [[XYPoint alloc] init];

    [myPoint setX:100 andY:200];

    [myRect setWidth:5 andHeigth:8];
    myRect.origin = myPoint;

    NSLog(@"Origin at (%i, %i)", myRect.origin.x, myRect.origin.y);


    [myPoint setX:50 andY:50];
    NSLog(@"Origin at (%i, %i)", myRect.origin.x, myRect.origin.y);

    XYPoint *theOrigin = myRect.origin;

    theOrigin.x = 200;
    theOrigin.y = 300;

     NSLog(@"Origin at (%i, %i)", myRect.origin.x, myRect.origin.y);

}
return 0;
}

我的矩形的原点改变了。这是输出:

Origin at (100, 200)
Origin at (100, 200)
Origin at (200, 300)
Program ended with exit code: 0

但是如果我做了类似的事情:

int a, b;
a = 5;
b = 6;
b = a;

a 的值将保持为 5,b 将变为 6。

我以为等号右边的值永远不变,而是设置等号左边的值。那么为什么当我这样做时:

XYPoint *theOrigin = myRect.origin;

    theOrigin.x = 200;
    theOrigin.y = 300;

为什么 myRect.origin 的值会改变? theOrigin 是一个指针,那么为什么改变指针的值会改变它指向的对象(myRect)呢?我的书上说 "return value is vulnerable." 是什么意思?如果我想在方法 myRect.origin 中制作一个副本,那么通过这样做:

XYPoint *theOrigin = myRect.origin;

    theOrigin.x = 200;
    theOrigin.y = 300;

myRect.origin 的值没有改变?

"does the value of myRect.origin change?"

是的,因为您正在修改同一个对象。 XYPoint *theOrigin 是一个指向对象的指针,它指向与 myRect.origin 相同的对象(这也是一个指针。)我建议阅读一些关于指针的内容,这将帮助您理解这种行为。 (别担心,指针本身非常简单。)