Kochan- Programming in objective-C.
Can’t understand two lines of code. (marked as “comments”)
XYPoint.h Interface File
#import <Foundation/Foundation.h>
@interface XYPoint: NSObject
{
int x;
int y;
}
@property int x, y;
-(void) setX: (int) xVal andY: (int) yVal;
@end
XYPoint.m Implementation File
#import "XYPoint.h"
@implementation XYPoint.h
@synthesize x, y;
-(void) setX: (int) xVal andY: (int) yVal
{
x = xVal;
y = yVal;
}
@end
Rectangle.h Interface File
#import <Foundation/Foundation.h>
@class XYPoint;
@interface Rectangle: NSObject
{
int width;
int height;
XYPoint *origin; // What does this line mean?
}
@property int width, height;
-(XYPoint *) origin;
-(void) setOrigin: (XYPoint *) pt;
-(void) setWidth: (int) w andHeight: (int) h;
-(int) area;
-(int) perimeter;
@end
Rectangle.m Implementation File
#import "Rectangle.h"
@implementation Rectangle
@synthesize width, height;
-(void) setWidth: (int) w andHeight: (int) h
{
width = w;
height = h;
}
–(void) setOrigin: (XYPoint *) pt
{
origin = pt;
}
–(int) area
{
return width * height;
}
–(int) perimeter
{
return (width + height) * 2;
}
–(XYPoint *) origin
{
return origin;
}
@end
Test Program
#import "Rectangle.h"
#import "XYPoint.h"
int main (int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Rectangle *myRect = [[Rectangle alloc] init];
XYPoint *myPoint = [[XYPoint alloc] init];
[myPoint setX: 100 andY: 200];
[myRect setWidth: 5 andHeight: 8];
myRect.origin = myPoint; // What does this line mean?
NSLog (@"Rectangle w = %i, h = %i", myRect.width, myRect.height);
NSLog (@"Origin at (%i, %i)",myRect.origin.x, myRect.origin.y);
NSLog (@"Area = %i, Perimeter = %i",
[myRect area], [myRect perimeter]);
[myRect release];
[myPoint release];
[pool drain];
return 0;
}
Output
Rectangle w = 5, h = 8
Origin at (100, 200)
Area = 40, Perimeter = 26
Kochan’s explanation of this line
myRect.origin = myPoint;
is: “After setting the width and the height of the rectangle to 5 and 8, respectively, you
invoked the setOrigin method to set the rectangle’s origin to the point indicated by
myPoint.”
But we didn’t invoked setOrigin!
is the same (almost) as
It’s just a different way of achieving the same result.
As Mahesh explained,
Declares a pointer (variable) called origin, of type XPoint.