u 오브젝트의 메모리 할당과 초기화

n         객체생성시 요구사항

동적으로 새로운 객체를 메모리에 할당

새롭게 메모리에 할당된 객체에 적절한 값들로 초기화

작성예

id anObject = [SomeClass alloc];

[anObject init];

[anObject someOtherMessage];

간략화

id anObject = [[SomeClass alloc] init];

[anObject someOtherMessage];

반환값 체크

id anObject = [[SomeClass alloc] init];

if ( anObject )

[anObject someOtherMessage];

else

...

 

n         NSObject alloc, allocWithZone

NSObject는 모든 클래스가 상속받게되는 최상위 클래스 (자바의 Object클래스)

생성한 클래스와 클래스내의 인스턴스 변수들을 위한 메모리 공간 확보

확보한 메모리공간을 생성한 인스턴스변수가 가르키도록 지시(Pointer)

모든 인스턴스 변수들의 값을 0으로 세팅

 

n         초기화 메소드 구현

초기화 인스턴스 메소드의 명칭은 init로 시작

인자가 없는 초기화 메소드는 init:

인자가 있는 초기화 메소드는 initMethodName:

 

n         초기화 메소드 작성예

- 인자가 없는 경우

- (id)init {

self = [super init];

if (self) {

creationDate = [[NSDate alloc] init];

}

return self;

}

 

 

- 인자가 있는 경우

 

- (id)initWithImage:(NSImage *)anImage {

NSSize size = anImage.size;

NSRect frame = NSMakeRect(0.0, 0.0, size.width, size.height);

self = [super initWithFrame:frame];

If (self) {

image = [anImage retain];

}

return self;

}

 

n         메모리확보와 초기화의 결합

convenience constructors를 사용함으로서 메모리 자동해제(autorelease)를 적용

자동해제의 경우 직접해제를 할경우 크래시 발생

Posted by 김반장78
,