In the implementation section for Rectangle when I left out #import "XYpoint" it still worked the same for me. Is putting #import "XYpoint" good practice or does it affect the program?
#import <Foundation/Foundation.h>
@interface XYPoint : NSObject
@property int x, y;
-(void) setX: (int) xVar andY: (int) yVar;
@end
#import "XYpoint.h"
@implementation XYPoint
@synthesize x, y;
-(void) setX:(int)xVar andY:(int)yVar {
x = xVar;
y = yVar;
}
@end
#import <Foundation/Foundation.h>
@class XYPoint;
@interface Rectangle: NSObject
-(XYPoint *) origin;
-(void) setOrigin: (XYPoint *) pt;
@end
#import "Rectangle.h"
#import "XYpoint.h"
@implementation Rectangle {
XYPoint *origin;
}
-(void) setOrigin:(XYPoint *)pt {
origin = pt;
}
-(XYPoint *) origin {
return origin;
}
@end
#import "XYpoint.h"
#import "Rectangle.h"
int main (int argc, char * argv[]) {
@autoreleasepool {
Rectangle *rect = [[Rectangle alloc] init];
XYPoint *pointy = [[XYPoint alloc] init];
[pointy setX:5 andY:2];
rect.origin = pointy;
NSLog(@"Origin %i %i", rect.origin.x, rect.origin.y);
}
return 0;
}
Your implementation of
Rectangledoesn’t use any of the specifics of theXYPointclass. It just treats it as a generic pointer and never messages it or dereferences it. Therefore, the forward declaration (the@classstatement in theRectangleinterface file) is sufficient. Importing the header doesn’t make any difference to the compiled program.It is quite likely that your
Rectangleclass will eventually evolve to care about the interface of theXYPointclass. When it does, it will need to import that interface declaration. The compiler will warn you if you neglect to import it.That said, there’s little reason not to import it.