티스토리 툴바


property 속성인 copy 과 retain

obj-c 2010/09/02 18:12 Posted by 자룡
The Objective-C Programming Language 를 보면 
property 의 속성을 nonatomic, copy 로 선언한 경우의, 대략적인 setter의 모습을 볼 수 있다.
@property (nonatomic, copy) NSString *string;
....
-(void)setString:(NSString *)newString {
    if (string != newString) {
        [string release];
        string = [newString copy];
    }
}
그렇다면 retain 은 다음과 같을것이다.
@property (nonatomic, retain) NSString *string;
....
-(void)setString:(NSString *)newString {
    if (string != newString) {
        [string release];
        string = [newString retain];
    }
}
결국 newString 의 값을 변경해도 괜찮은지 아닌지의 차이가 되버린다.
저작자 표시 비영리 변경 금지
다음과 같은 프로퍼티 선언이 있다.
@property (nonatomic, readonly, retain) NSString* name;
readyonly 는 setter 를 만들지 않는다는 말이고, 
retain 은 setter 를 만들때 레퍼런스 카운팅을 하나 증가시킨다는 말이다.

setter 를 만들지 않는데, 굳이 retain 속성을 주는 이유는 뭘까?

The Objective-C Programming Language 문서의 Declared Properties 섹션의 Property Re-declaration 을 보면 그 이유를 찾아볼 수 있다.

You can re-declare a property in a subclass, but (with the exception of readonly vs. readwrite) you must repeat its attributes in whole in the subclasses. The same holds true for a property declared in a category or protocol —while the property may be redeclared in a category or protocol, the property’s attributes must be repeated in whole.

한마디로 프로퍼티를 재정의할때는 readonly, readwrite 를 제외한 기존의 모든 속성을 그대로 가지고 와야 한다는 것.

그러므로 위의 name 프로퍼티를 클래스 외부에서는 읽기만 가능하게 하고, 클래스 내에서는 쓰기도 가능하게 하려면, 다음과 같이 재정의를 해야 하며, 이런 경우에 retain 과 readonly 속성을 같이 쓰게 되는 것이다.

// public header file 
@interface Sample : NSObject {     
    NSString* name;
} 
@property (nonatomic, readonly, retain) NSString* name; 
@end 

// private implementation file 
@interface Sample ()
@property (nonatomic, readwrite, retain) NSString* name;
@end 

@implementation Sample
@synthesize name;
@end
저작자 표시 비영리 변경 금지
기존에 사용하던 SCPlugin 이 윈도우용 Tortoise 와 비슷하긴 하지만
뭔가 좀 불편한점이 있어서 다른 클라이언트는 없는지 찾아보다 발견한 녀석이다.

http://zigzig.com/

non-commercial 용 라이센스는 신청하면 이메일로 바로 보내준다. :)
저작자 표시 비영리 변경 금지