Reference Count

  Objective-C에서의 메모리 관리는 reference count(retain count)라는 개념에 의해서 이루어진다. Reference count는 해당 object에 대한 reference가 몇개 있는지 나타내는 것으로서, new, alloc, copy 등에 의하여 메모리 공간이 할당되고 새로운 object가 생성되면 reference count는 1이 된다. 그 object에 대한 참조가 늘어날때 마다 count도 하나씩 증가하고 참조가 없어질 때마다 count는 하나씩 감소하며 count가 0이 되는 순간, 즉 아무것도 그 object를 참조하지 않게 되면 자동적으로 dealloc 메소드가 호출되어 그 object는 사라지고 그것이 차지하고 있던 메모리 공간이 반환된다.

  NSObject는 다음과 같은 메소드를 갖고 있다.

    - (id) retain;  /* retainCount++, return self. 

                     * Used when you want to prevent it from being deallocated 

                     * without your express permission. */

    - (void) release;  /* retainCount-- */

    - (unsigned) retainCount;  /* return retainCount */



Autorelease

  효율적인 메모리 관리와 메모리 누수 방지를 위하여 메모리 공간의 할당 및 반환을 제때 잘 해주어야한다. 그러나 프로그래머로서는 누가 언제 어떤 메모리 공간을 할당, 반환해야하는지 아는 것이 쉽지 않다. Cocoa는 메모리 관리를 보다 간단히 해주기 위한 수단으로서 autorelease와 autorelease pool을 제공한다.

    - (id) autorelease;


  autorelease 선언된 object는 autorelease pool에 담기게 되고, 후에 autorelease pool이 release 또는 drain되면 pool에 담긴 모든 object에게 release 메세지를 날리게 된다. 다음의 메소드를 보자. 

    - (NSString*) description 

    {

        NSString* str = [[NSString allocinitWithFormat@"I am %d years old"4];

        return str;

    }


  위의 description 메소드는 NSString 객체를 alloc으로 생성하고 그 값을 초기화한 뒤 리턴하고 있다. 리턴된 str 객체는 프로그램의 다른 부분에서 사용될 것이다. 그렇다면 이 str을 사용한 뒤 release는 언제 어디에서 해주어야 하는가. 이러한 문제는 str 객체에 대하여 autorelease 선언을 해줌으로써 해결할 수 있다. 즉 위 코드의 마지막 줄을

 

    return [str autorelease];

  
로 바꿈으로써, 나중에 str이 담겨있는 autorelease pool을 release할 때 str이 release될 수 있도록 할 수 있다.



The Rules of Cocoa Memory Management

  Object는 몇 line의 코드에 걸쳐 잠시 일시적으로 사용되는 transient object와 메소드 호출 등으로 일정 시간동안 프로그램의 여러 부분에서 사용되는 hang on object로 구분할 수 있다. 이 두 가지 object의 메모리는 다음의 규칙에 의해 관리하는 것이 Cocoa의 convention이다.
    

- alloc/new/copy로 생성된 transient object
  사용 후 바로 release해준다.
    

    NSMutableArray* array = [[NSMutableArray allocinit];


    /* use the array */


    [array release];


- 그 외의 방법으로 생성된 transient object
  retain count는 1, 이미 autorelease 선언된 것으로 가정한다. 사용 후 아무것도 안해주어도 된다.

    NSMutableArray* array = [NSMutableArray arrayWithCapacity17];


    /* use the array */



- alloc/new/copy로 생성된 hang on object
  dealloc 메소드 안에서 release해준다.

    - (void) doStuff

    {

        // array is an instance variable

        array = [NSMutableArray new];

    }


    - (void) dealloc

    {

        [array release];

        [super release];

    }



- 그 외의 방법으로 생성된 hang on object
  retain count는 1, 이미 autorelease 선언된 것으로 가정한다. 생성 후 retain해주고, 사용 후 dealloc에서 release해준다.

    - (void) doStuff

    {

        // array is an instance variable

        array = [NSMutableArray arrayWithCapacity17];

        [array retain];

    }


    - (void) dealloc

    {

        [array release];

        [super release];

    }


'Object-C' 카테고리의 다른 글

textbox 글자수에 따른 height 가져오기  (0) 2010.11.26
HIG  (0) 2010.11.07
StanFord Lecture PDF  (0) 2010.10.29
테이블뷰 정렬  (0) 2010.10.23
키보드 사이즈 이벤트  (0) 2010.10.23

+ Recent posts