그림은 티스토리 원문 ↗과 함께 볼 수 있습니다.

셀렉터로 메서드를 식별하는 방법과 프로퍼티로 데이터에 접근하는 방법을 예제로 정리한다.

셀렉터

  • 클래스에 선언된 메소드 구별하기
  • 메서드는 이름과 인자 레이블을 포함한 셀렉터로 구분한다.
  • 메소드 선언
  • -(NSUInteger)length
  • 셀렉터
  • length

ex)

-(NSComparisonResult)compare:(NSString *)string 셀렉터 => compare:
-(NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask 셀렉터 => compare:options:
-(NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask range:(NSRange)compareRange 셀렉터 => compare:options:range:

컴파일드 셀렉터

  • 코드로 셀렉터 사용
  • 형태: @selector(xxx)
  • SEL 타입
  • SEL s = @seletor(length);
  • 셀렉터 실행 메소드
  • -(NSComparisonResult)compare:(NSString *)string
  • -(NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask
  • -(NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask range:(NSRange)compareRange
  • (컴파일드) 셀렉터
  • SEL s1 = @selector(compare:);
  • SEL s2 = @selector(compare:options:);
  • SEL s3 = @selector(compare:options:range:);
  • 셀렉터 실행 메소드
  • -(id)perfromSelector:(SEL)aSelector
  • -(id)performSelector:(SEL)aSelector withObject:(id)object
  • -(id)performSelector:(SEL)aSelector withObject:(id)onject1 withObject:(id)object2
  • 셀렉터로 메소드 호출
SEL s = @selector(length);
[obj performSelector:s];
  • 메소드 작성 여부를 체크
  • -(BOOL)respondsToSelector:(SEL)aSelector
  • 체크 후 호출 예제
id([obj respondsToSeletor:s]){
    [obj performSelector:s];
}

예제) NSString에 정의된 메소드와 셀렉터 사용

NSString *str = @"hello world";

SEL s = @selector(uppercaseString);
if([str respondsToSelector:s] {
    NSString *str2 = [str performSelector:s];
    NSLog(@"Upper Case : %@", str2);
}

프로퍼티

1. 프로퍼티 선언과 사용

  • 프로퍼티: 점(.)을 이용해서 데이터에 접근
  • 클래스 선언부에 프로퍼티 선언
  • @property([프로퍼티 속성]) [타입] [이름];
  • Rectangle 클래스 프로퍼티 선언 코드
@inerface Rectangle: NSObject
@property int width;
@property int height;
@end
  • 구현파일
@implementation Rectangle
@end
  • 프로퍼티 사용하기
Rectangle *obj = [[Rectangle alloc]init];
// 프로퍼티로 값 설정하기
obj.width = 10;
obj.height = 20;
//프로퍼티 값 가져오기
int w = obj.width;
  • 클래스 내부: self로 프로퍼티 사용
@implementation Rectangle
-(int)size {
    return self.width *height;
}
@end

2. 프로퍼티와 멤버 변수

  • 프로퍼티 선언 -> 언더바(_) + 프로퍼티 이름의 멤버 변수
@implementation Rectangle
-(int)size{
    return _width*_height;
}
@end
  • synthesize: 멤버 변수 이름 설정
  • 클래스 구현부에 @synthesize 작성
  • @synthesize [프로퍼티 이름];
  • @synthesize [프로퍼티 이름] = [멤버 변수 이름];
  • 멤버 변수의 이름을 프로퍼티의 이름과 같게 설정
@implementation Rectangle
@synthesize width;
-(int)size{
    return width*_height;
}
@end
  • 멤버 변수의 이름을 별도로 설정
@implementation Rectangle
@synthesize width;
@synthesize height = rectangleHeight;
-(int)size{
    return width*retangleHeight;
}
@end
  • 멤버 변수와 프로퍼티를 각각 선언할 때는 width와 _width처럼 서로 다른 변수가 만들어지는지 확인한다.
  • 멤버 변수 선언과 프로퍼티 선언을 함께 하려면 synthesize로 프로퍼티와 멤버 변수 일치
@implementation Rectangle
@synthesize width;
-(int)size{
    return width * _height;
}
@end

3. 프로퍼티 속성

  • 프로퍼티 속성
  • @property([속성 수식자])[프로퍼티 타입][프로퍼티 이름];

속성 종류

  • 읽기/쓰기 제어
  • readonly: 읽기 전용
  • readwrite: 읽기/쓰기 가능(기본, 생략 가능)
  • @property (readwrite) int width;
  • @property (readonly) int size;
  • 쓰레드 접근 제어
  • atomic: 합성된 getter·setter의 개별 값 접근을 원자적으로 처리한다(기본값). 객체 전체의 스레드 안전성이나 여러 프로퍼티 사이의 일관성을 보장하지는 않는다.
  • nonatomic: 쓰레드 접근 제어 사용 안함
  • @property (nonatomic) int width;

4. 프로퍼티와 게터/세터 메소드

  • 프로퍼티 선언 -> 게터와 세터 메소드 생성
  • 프로퍼티로 값 얻어오기 -> 게터 메소드 동작
  • 프로퍼티로 값 설정 -> 세터 메소드 동작
Rectangle *r = [[Rectangle alloc]init];
[r setWidth:20];
r.height = 30;
  • 프로퍼티 속성에 게터/세터 메소드 이름 설정
  • getter=[게터 메소드 셀렉터]
  • setter=[세터 메소드 셀렉터]
  • width 게터와 세터 메소드 이름 설정하기 -> 일반적으로 세터는 안한다
  • @property (getter = getWidth, setter = setRectangleWidth:) int width;
  • 프로퍼티를 이용한 값 설정과 얻어오기 : 기본 행위
  • 별도의 동작 -> 게터와 세터 메소드를 별도로 작성
  • 예) 사각형의 가로 길이는 0보다 작으면 안된다.
-(void)setWidth:(int)newWidth{
    if(newWidth<0)
    	_width = 0;
    else
    	_width = newWidth;
}
  • 프로퍼티의 사용 -> 세터 메소드 동작
Rectangle *r1 = [[Rectangle alloc]init];
r1.width = -100;
  • 직접 작성한 getter·setter에서 같은 프로퍼티를 다시 호출하면 재귀 호출이 생길 수 있다.
-(void)setWidth:(int)newWidth{
    self.width = newWidth;
}
  • _멤버 변수 사용할 것

티스토리에 쓴 글을 이곳의 문체와 구성에 맞춰 다시 정리했습니다. 원문 보기 ↗ 원문에 포함된 일부 이미지와 서식은 원문 링크에서 확인할 수 있습니다.