그림은 티스토리 원문 ↗과 함께 볼 수 있습니다.
사각형 클래스를 예제로 Objective-C의 선언부와 구현부를 나눠 작성한다. 메서드의 인자·반환값과 self 사용도 함께 연습한다.
1. 클래스 파일 만드는 방법
1-1. New File 생성
1-2. Cocoa Class 선택
1-3. Subclass of, Class 셋팅
1-4. 클래스 선언은 .h 헤더 파일에, 메서드 구현은 .m 파일에 작성한다.
클래스 선언부(.h)
- 클래스의 행위를 알리는 역할
- 형식
`@interface Rectangle : NSObject
@end`클래스 구현부(.m)
- 클래스의 행위 동작 코드 작성
- 형식
`#import "Rectangle.h"
@implementation Rectangle
@end`멤버 변수 선언
- 클래스에서 다루는 데이터
- 클래스 선언부(.h)에 선언하기 -> 공개하고 싶을 때
`@interface Rectangle : NSObject {
int width;
}
@end`- 클래스 구현부(.m)에 선언하기 -> 공개하고 싶지 않을 때
`@implementation Rectangle {
int width;
}
@end`- 선언부와 구현부 둘 중 하나만 작성하면 된다 -> 둘다 적으면 중복으로 에러가 뜸
2. 메소드
2-1. 메소드 선언 및 구현
메소드란?
- 클래스가 수행하는 행위
- 메소드는 선언(declaration) -> 클래스 해더에 선언, 구현(implementation)으로 나뉘어 진다.
size 메소드 : 사각형 클래스에 넓이 구하는 행위 작성
메소드 선언
`@interface Rectangle : NSObject {
int height, width;
}
-(int)size;
@end`메소드 구현
`@implementation Rectangle
-(int)size {
return width * height
}
@end`2-2. 인스턴스 메소드와 클래스 메소드
| 인스턴스 메소드 | 클래스 메소드 구별하기 | - 기호로 시작 | + 기호로 시작 메시지 리시버 | 객체 | 클래스 멤버 변수 접근 | 가능 | 불가능 선언 예제 | -(void)method1; | +(void)method2; 사용 예제 | [obj method1[ | [Class method2]
2-2-1. 인스턴스 메소드 선언
`@interface MyClass : NSObject
-(void)instanceMethod;
@end`- 인스턴스 메소드 사용, 객체 생성 필요
`Retangle *rect = [[Rectangle alloc]init];
int area = [rect size];`- 멤버 변수에 접근 가능
`-(int)size {
return width * height;
}`2-2-2. 클래스 메소드 선언
`@interface MyClass: NSObject
+(void)classMethod;
@end`- 클래스 메소드 사용, 객체 생성 불필요
`[MyClass classMethod];`- 클래스 메소드는 멤버 변수에 접근 불가: ERROR
`+(int)size {
// return width * height; -> 접근 불가
}`2-3. 메소드 실행 결과
- 메소드 실행 결과를 반환
- 반환값의 타입에 맞도록 선언
`-(int)method1;
-(NSString *)method2;`- 반환값이 없으면 void
`-(void)method3;`- 메소드 구현
`-(int)method2 {
int ret;
// code
return ret;
}
-(void)method3 {
//code
return;
}`2-4. 메소드 파라미터
- 클래스에 정의한 메소드에 정보 전달
- 예) 사각형의 가로 길이 설정 행위 -> 가로 길이 정보 필요
- 형식) 파라미터 레이블 : (타입) 파라미터 변수 이름
- 파라미터가 있는 메소드 선언
`-(void)setWidth:(int)newWidth;
-(void)setWidth:(int)newWidth height:(int)newHeight;`- 파라미터가 있는 메소드 구현
`-(void)setWidth: (int)newWidth {
width = newWidth;
}
-(void)setWidth: (int)newWidth height:(int)newHeight {
width = newWidth;
height = newHeight;
}`2-5. 데이터 입출력 메소드
- 클래스의 데이터 : 보호(캡슐화)
- 클래스 외부에서 값을 읽거나 설정할 때 getter·setter를 사용한다.
- setter 메소드 : 데이터 값을 설정하기 위한 의도
- getter 메소드 : 데이터 값을 얻어오기 위한 의도
setter
- 메소드 이름 : set + 변수이름(첫 글자를 대문자로 변경)
- 반환값은 void, 변수 타입 파라미터
- Rectangle 클래스에 가로 길이 설정 메소드
`-(void)setWidth:(int)newWidth;`- 메소드 구현
`-(void)setWidth:(int)newWidth {
width = newWidth;
}`getter
- 메소드 이름 : 변수 이름과 같다
- 반환값은 멤버 면수와 같은 타입, 파라미터 없다!
- Rectangle 클래스에서 가로 길이 얻는 메소드
`-(int)width;`- 메소드 구현
`-(int)width {
return width;
}`사각형 실습 해보기
- 사각형 클래스 생성
- 사각형의 가로와 세로 길이 정보
- 사각형의 넓이 계산 행위
- 크기 20 * 30 사각형의 넓이 구하기
선언부(.h)
구현부(.m)
main
2-6. 포인터 self
- 객체에 접근하기
- 클래스 외부에서 포인터 변수로 다루기
`Rectangle *rect = [[Rectangle alloc] init];
[rect size];`- 클래스 내부 코드에서 다루기 : self
`@implementation Rectangle
-(void)setWidth:(int)newWidth {
width = newWidth;
}
-(void)setWidth:(int)newWidth height:(int)newHeight {
[self setWidth:newWidth]
[self setHeight:newHeight]
}
@end`self 실습해보기
- 가로와 세로 길이를 동시에 설정(self) 사용
- 정사각형을 판단하는 행위 추가
- isSquare
선언부(.h)
`#import <Foundation/Foundation.h>
@interface Rectangle : NSObject {
int height, width;
}
-(void)setWidth:(int)newWidth;
-(int)width;
-(void)setHeight:(int)newHeight;
-(int)height;
-(int)size;
-(void)setWidth:(int)newWidth height: (int)newHeight;
-(BOOL)isSquare;
@end`구현부(.m)
`#import "Rectangle.h"
@implementation Rectangle- (BOOL)isSquare {
if ( width == height )
return YES;
else
return NO;
return width == height;
}
-(void)setWidth:(int)newWidth height:(int)newHeight {
[self setWidth: newWidth];
[self setHeight: newHeight];
}
-(void)setWidth:(int)newWidth {
width = newWidth;
}
-(int)width {
return width;
}
-(void)setHeight:(int)newHeight {
height = newHeight;
}
-(int)height {
return height;
}
-(int)size {
return width * height;
}
@end`main
`#import <Foundation/Foundation.h>
#import "Rectangle.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Rectangle *r1 = [[Rectangle alloc] init];
[r1 setWidth:10];
[r1 setHeight:20];
NSLog(@"r1 isSquare : %d", [r1 isSquare]);
Rectangle *r2 = [[Rectangle alloc] init];
[r2 setWidth:10 height:10];
NSLog(@"r2 isSquare : %@", [r2 isSquare] ? @"YES" : @"NO");
Rectangle *rect = [[Rectangle alloc] init];
[rect setWidth:20];
[rect setHeight:30];
[rect setWidth:30 height:40];
NSLog(@"width : %d, height : %d", [rect width], [rect height]);
int size = [rect size];
NSLog(@"Rectangle(20*30) size : %d", size);
}
return 0;
}`실행 결과