Interface file XYPoint.h
#import <Foundation/Foundation.h>
@interface XYPoint : NSObject <NSCopying>
{
int x;
int y;
}
@property int x, y;
-(void) setX: (int) xVal andY: (int) yVal;
-(id) copyWithZone:(NSZone *)zone;
@end
The related method from the XYPoint implementation file:
-(id) copyWithZone:(NSZone *)zone
{
XYPoint *newXYPoint = [[XYPoint allocWithZone:zone] init];
[newXYPoint setX:x andY:y];
return newXYPoint;
}
Interface file Rectangle.h
#import <Foundation/Foundation.h>
#import "XYPoint.h"
@interface Rectangle : NSObject <NSCopying>
{
int width;
int height;
XYPoint *origin;
}
@property int width, height;
-(id) initWidth: (int) w andHeight: (int) h;
-(void) setOrigin: (XYPoint *) pt;
-(XYPoint *) origin;
-(int) area;
-(int) perimeter;
-(void) setWidth:(int)w andHeight:(int) h;
-(void) dealloc;
-(id) copyWithZone:(NSZone *)zone;
The related method from the Rectangle implementation file:
-(id) copyWithZone:(NSZone *)zone
{
Rectangle *newRectangle = [[Rectangle allocWithZone:zone] initWidth:width andHeight:height];
[newRectangle setOrigin: [origin copy]];
return newRectangle;
}
The main.m file for testing:
#import <Foundation/Foundation.h>
#import "Rectangle.h"
int main (int argc, const char * argv[])
{
@autoreleasepool {
// insert code here...
XYPoint *origin1 = [[XYPoint alloc] init];
[origin1 setX:10 andY:10];
Rectangle *rectangle1 = [[Rectangle alloc] initWidth:10 andHeight:10];
[rectangle1 setOrigin:origin1];
// Create copy //
Rectangle *rectangle2 = [rectangle1 copy];
[[rectangle2 origin] setX:100 andY:100];
[rectangle2 setWidth:100 andHeight:100];
// Display both rectangles //
NSLog(@"Rectangle1, width: %i, height: %i", [rectangle1 width], [rectangle1 height]);
NSLog(@"Has origin, x: %i, y: %i", [[rectangle1 origin] x], [[rectangle1 origin] y]);
NSLog(@"Rectangle2, width: %i, height: %i", [rectangle2 width], [rectangle2 height]);
NSLog(@"Has origin, x: %i, y: %i", [[rectangle2 origin] x], [[rectangle2 origin] y]);
}
return 0;
}
A) Does it make sense to implement both mutable and immutable copies for these classes:
It does not, as both width and height and both x and y are not objects.
Maybe somebody else can give a better explanation?