I am working through the XYPoint example and I synthesized XYPoint instead of creating my own setter method. When I synthesize XYPoint it appears the synthesized setter method is copying a memory address since I can change my XYPoint by changing myOrigin. Is there something I am doing wrong?
@interface
#import <Foundation/Foundation.h>
@class XYPoint;
@interface Rectangle : NSObject
@property int width;
@property int height;
@property (strong, nonatomic) XYPoint *origin;
-(int) area;
-(int) perimeter;
//-(XYPoint *) origin; // Getter method. Returns the XYPoint.
//-(void) setOrigin: (XYPoint *) theOrigin;
@end
@implementation
#import "Rectangle.h"
#import "XYPoint.h"
@implementation Rectangle
/*{
XYPoint *origin;
}*/
@synthesize width;
@synthesize height;
@synthesize origin;
-(int) area
{
return self.width * self.height;
}
-(int) perimeter
{
return 2 * (self.width + self.height);
}
/*
-(XYPoint *) origin
{
return origin;
}
-(void) setOrigin: (XYPoint *) theOrigin
{
if (origin == nil)
{
origin = [[XYPoint alloc] init];
}
origin.x = theOrigin.x;
origin.y = theOrigin.y;
}
*/
@end
main
#import <Foundation/Foundation.h>
#import "Rectangle.h"
#import "XYPoint.h"
int main(int argc, const char * argv[])
{
@autoreleasepool
{
Rectangle *myRect = [[Rectangle alloc] init];
XYPoint *myOrigin = [[XYPoint alloc] init];
myRect.width = 5;
myRect.height = 10;
myOrigin.x = 50;
myOrigin.y = 100;
myRect.origin = myOrigin;
NSLog(@"The rectangles width is %i, and the height is %i", myRect.width, myRect.height);
NSLog(@"The rectangles area is %i, and the perimeter is %i", [myRect area], [myRect perimeter]);
NSLog(@"The origin is at (%i, %i)", myRect.origin.x, myRect.origin.y);
myOrigin.x = 100;
myOrigin.y = 200;
NSLog(@"The origin is at (%i, %i)", myRect.origin.x, myRect.origin.y);
}
return 0;
}
Output
2012-04-29 19:00:21.079 Rectangles[39480:403] The origin is at (50, 100)
2012-04-29 19:00:21.081 Rectangles[39480:403] The origin is at (100, 200)
Take care,
Jon