본문 바로가기

C/Objective C/Objective C

Objective C @Class 지시어 예제 따라하기 - @Class 지시어를 이용한 간단한 예제이다.- 소스코드#import @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 @class XYPoint; @interface Rectangle : NSObject{ int width; int height; XYPoint *origin; } @property in.. 더보기
Objective C method overriding(메소드 재정의) 예제 따라하기 메서드 재정의하기 상속받은 메서드를 ‘재정의’하여 메서드 정의를 변경할 수 있다. 앞서 본 클래스 ClassA와 ClassB로 돌아 가서 initVar 메서드를 ClassB에 작성하고 싶다고 하자. 이미 ClassB는 ClassA에 정의된 initVar 메서드 를 상속받는다는 것을 알 것이다. 이 상속받은 메서드를 제거하고 동일한 이름으로 새 메서드를 만들 수 있을까? 대답은 ‘그렇다’이다. 그저 동일한 이름으로 메서드를 새로 정의하기만 하면 된다. 부모 클래스에 있는 메서드와 동일한 이름으로 메서드를 정의하면, 새로운 내용이 상속받은 메서드를 대치 하거나 재정의한다. 새 메서드는 반환 형, 인수 개수, 데이터 형이 재정의하는 메서드와 같아야 한다.- 소스코드 #import @interface Class.. 더보기
Objective C 상속 예제 따라하기 두번째 - 도형에 관한 상속 예제이다.- 소스코드#import @interface Rectangle : NSObject{ int width; int height; } @property int width, height; -(int)area; -(int)perimeter; -(void)setWidth:(int) w andHeight: (int) h; @end #import "Rectangle.h" @implementation Rectangle @synthesize width, height; -(int)area{ return width*height; } -(int)perimeter{ return (width+height)*2; } -(void)setWidth:(int) w andHeight: (int) h{ widt.. 더보기
Objective C 상속 예제 따라하기 상속 모든 것은 루트에서 시작된다. 지금까지 정의한 클래스는 모두 NSObject라는 루트 클래스의 자식들이다. 이를 인터페이스 파일에서 다음 과 같이 지시해 주었다. @interface Fraction:NSObject ... @end Fraction 클래스는 NSObject 클래스에서 파생되었다. 계층도를 보면 NSObject가 최상위에 있기 때문에 (즉, 그 위로 아무 클래스도 없기 때문에) ‘루트’ 클래스라고 부른다. Fraction 클래스는 ‘자식 클래스’ 혹 은 ‘서브클래스’라고 부른다.- 소스코드#import @interface ClassA : NSObject { int x; } -(void) initVar; @end #import "ClassA.h" @implementation ClassA .. 더보기