보관물

Posts Tagged ‘Synthesize’

Custom classes, Properties

2월 20, 2011 댓글 남기기

Object Classes

Public Header (.h)

#import <Foundation/Foundation.h>

@interface Animal : NSObject
{

//instance variables
NSString *name;

}
//method declarations
-(NSString *)name;
-(void)setName:(NSString *)m_name;
@end

Private Implementation (.m)

#import “Animal.h”

@implementation Animal
-(NSString *)name {

return name;

}
-(void)setName:(NSString *)m_name {

name = m_name;

}
@end

Class내에서 선언된 method를 사용하고자 하는 경우 다음과 같은 형태로 사용한다.

[self setName:@”Andy”];

if ([self isDog]) {
//…
}

Properties

위의 sample code는 NSString 형태의 name이라는 변수에 대해서 getter/setter를 구현하였음.
이를 Properties와 Synthesize를 써서 같은 기능을 하도록 변경을 하면 다음과 같다.

Public Header (.h)

#import <Foundation/Foundation.h>

@interface Animal : NSObject
{

//instance variables
NSString *name;

}

@property (copy) NSString *name;

@end

Private Implementation (.m)

#import “Animal.h”

@implementation Animal

@synthesize name;

@end

ivars에서 정의한 이름과 property로 사용할 이름을 다르게 정의할 수도 있다.
아래의 sample code는 ivar는 _name으로 정의하였지만
property를 다음과 같이 정의함으로써 name으로 사용할 수있다.

Public Header (.h)

#import <Foundation/Foundation.h>

@interface Animal : NSObject
{

//instance variables
NSString *_name;

}

@property (copy) NSString *name;

@end

Private Implementation (.m)

#import “Animal.h”

@implementation Animal

@synthesize name = _name;

@end

property로 선언한 것을 self와 dot syntax를 활용할 수도 있다.

//self와 dot syntax를 사용한 경우
self.name = @”Lucy”;

//self와 dot syntax를 사용한 경우와 동일한 내용
[self setName:@”Lucy”];

//ivar에 직접 접근하는 경우 (accessor method를 사용안함)
name = @”Lucy”;

그러므로 self와 dot syntax를사용하고 setter를 별도로 구현하는 경우 다음의 경우를 주의해야한다.

-(void) setName:(NSString *)m_name {

//self.name은 [self setName:…]을 호출하므로 재귀적으로 무한루프에 빠지게됨
self.name = m_name;

}

참고자료

iPhone Application Development (CS193P) – Winter 2010 : iTunes U
3. Custom Classes, Object lifecycle, Autorelease, Objective-C Properties