프로그래밍/Objective C

Objective C - @class 지시어 사용하기

가카리 2015. 9. 15. 22:01
반응형

@class지시어를 사용하면 그 클래스 형식의 인스턴스 변수를 만나게 될 때 컴파일러에게 그 클래스가 무엇인지 알려준다.

 

이것대신 헤더파일을 import해도 상관 없다.

 

Rectangle.h

#import <Foundation/Foundation.h>

 

@classXYPoint;//이러한 클래스가 쓰인다는 것만 알려줌 대신 import 헤더파일을 불러와도

 

@interface Rectangle: NSObject

 

@property int width, height;

 

-(XYPoint *) origin;//추가됨

-(void) setOrigin: (XYPoint *) pt;

-(int) area;

-(int) perimeter;

-(void) setWidth: (int) w andHeight: (int) h;

@end

 

Rectangle.m

#import "Rectangle.h"

 

@implementation Rectangle

{

    XYPoint *origin;

}

@synthesize width, height;

 

-(void) setWidth: (int) w andHeight: (int)h{

    width = w;

    height = h;

}

 

-(void) setOrigin:(XYPoint *)pt{//origin 초기화메소드

    origin = pt;

}

 

-(int) area{

    returnwidth*height;

}

 

-(int) perimeter{

    return (width + height) * 2;

}

-(XYPoint *) origin{

    return origin;

}

@end

 

XYPoint.h

#import <Foundation/Foundation.h>

 

@interface XYPoint: NSObject

 

@propertyint x, y;

//setX xVal 저장됨 andY yVal 저장됨

-(void) setX: (int) xVal andY: (int) yVal;

 

@end

 

XYPoint.m

#import "XYPoint.h"

 

@implementation XYPoint

 

@synthesize x, y;

 

-(void) setX:(int)xVal andY:(int)yVal{

    x = xVal;

    y = yVal;

}

 

@end

 

main.m

 

#import <Foundation/Foundation.h>

#import "Rectangle.h"

#import "XYPoint.h"

 

int main(int argc, const char * argv[]) {

    @autoreleasepool {

        Rectangle *myRect = [[Rectangle alloc] init];

        XYPoint *myPoint = [[XYPoint alloc] init];

        

        [myPoint setX: 100 andY: 200];

        

        [myRect setWidth: 5 andHeight: 8];

        myRect.origin = myPoint;

        

        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]);

        

    }

    return 0;

}

 

실행 화면

 

 

반응형