0

The author wrote that whenever the value of point changes the value of myRect's origin will change as well, but I don't understand how turning origin into an object fixes it. What's the difference between creating an object and a pointer?

Fixed setOrigin method:

-(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;
}
1
  • 3
    I think you're confused... This entire thing is implemented with objects (and fairly well, at that). Pointers merely point to the object. What's the alternative, a struct? Commented Jun 16, 2012 at 15:01

1 Answer 1

2

XYPoint *origin; is a pointer to the object that contains x and y. In this case in particular you have two references that point to the same exact object. myRect.origin and point point to the same XYpoint object. What this means is if you change the value of x or y by either means (myRect.origin.x = 1 or point.x = 1), the updated x and y will be when accessed either way (myRect.origin or point).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.