본문 바로가기

C/Objective C/Objective C

Objective C @Class 지시어 예제 따라하기

- @Class 지시어를 이용한 간단한 예제이다.

- 소스코드

#import <Foundation/Foundation.h>


@interface XYPoint : NSObject

{

int x;

int y;

}

@property int x,y;

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

@end 

#import "XYPoint.h"


@implementation XYPoint

@synthesize x,y;

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

x = xVal;

y = yVal;

}

@end

 

#import <Foundation/Foundation.h>


@class XYPoint;

@interface Rectangle : NSObject{

int width;

int height;

XYPoint *origin;

}

@property int width, height;

-(XYPoint *) origin;

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

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

-(int) area;

-(int) perimeter;


@end 

#import "Rectangle.h"


@implementation Rectangle

@synthesize width, height;

-(XYPoint *) origin{

return  origin;

}

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

origin = pt;

}

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

width = w;

height = h;

}

-(int) area{

return width * height;

}

-(int) perimeter{

return (width + height) * 2;

}

@end 

#import <Foundation/Foundation.h>

#import "XYPoint.h"

#import "Rectangle.h"

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

{

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

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

[myPoint setX:100 andY:200];

[myRect setWidth:5 andHeight:8];

myRect.origin = myPoint;

NSLog(@"Origin at(%i, %i)", myRect.origin.x, myRect.origin.y);

NSLog(@"Area = %i, Perimeter = %i",[myRect area], [myRect perimeter]);

    return 0;

} 

@class 지시어를 사용하면, Rectangle에서 XYPoint 형식의 인스턴스 변수를 만나게 될 때, 컴파일러에게 그 클래스가 무엇인지 알려준다. setOrigin:과 origin 메서드에서도 클래스 이름을 인수와 반환 값을 선언 하는데 사용한다.
@class를 쓰는 대신에 다음과 같이 헤더 파일을 임포트하는 방법도 있다.

#import “XYPoint”
@class 지시어를 달면 컴파일러가 XYPoint.h 파일 전체를 처리할 필요가 없어지기 때문에 좀 더 효율적 이다. 컴파일러는 그저 XYPoint가 클래스 이름이라는 것만 알고 있으면 된다. 만일 XYPoint 클래스의 메 서드를 사용해야 한다면, 컴파일러에게 더 많은 정보가 필요하기 때문에 @class 지시어로는 충분하지 않 다. 이때 컴파일러는 메서드가 인수를 얼마나 많이 받는지, 인수가 어떤 형인지, 어떤 값을 반환하는지에 대한 정보를 알아야 한다. 


- 실행화면