0

作者写道,每当值point变化时,值myRect's origin也会变化,但我不明白origin变成对象是如何解决它的。创建对象和创建指针有什么区别?

固定setOrigin方法:

-(void) setOrigin:(XYpoint *)pt {
    if (! origin)
        origin = [[XYpoint alloc] init];

    origin.x = pt.x;
    origin.y = pt.y;
}

#import <Foundation/Foundation.h>

@interface XYPoint : NSObject 
@property int x, y;

@end

#import "XYpoint.h"

@implementation XYPoint
@synthesize x, y;

@end

#import <Foundation/Foundation.h>

@class XYPoint;
@interface Rectangle: NSObject

-(void) setOrigin: (XYPoint *) pt; 

@end

#import "Rectangle.h"
#import "XYpoint.h"

@implementation Rectangle {
    XYPoint *origin;
}

-(void) setOrigin:(XYPoint *)pt {
    origin = pt;
}

@end

#import "XYpoint.h"
#import "Rectangle.h"

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

        point.x = 3;
        point.y = 8;

        [myRect setOrigin: point];
    }
    return 0;
}
4

1 回答 1

2

XYPoint *origin;是指向包含x和的对象的指针y。特别是在这种情况下,您有两个指向同一个确切对象的引用。myRect.originpoint指向同一个XYpoint对象。这意味着如果您更改xy通过任何一种方式(myRect.origin.x = 1point.x = 1)的值,则更新x的值y将在以任何一种方式(myRect.originpoint)访问时被更新。

于 2012-06-16T15:04:42.123 回答