티스토리 뷰

iOS 4.3미만 또는 macOS 10.6(Snow Leopard) 이하의 버전에서는 ARC를 사용 할 수 없기때문에 해당 버전을 지원해야하는 프로그램 또는 어떤 사정에 의해서 ARC를 사용하지 않는 프로그램에서는 메뉴얼로 메모리 관리를 해주어야한다.(Menual Retain Count)
이 정리는 어디까지나 프레임워크에서 객체의 라이프사이클의 동작을 보기위함이므로 MRC에 대해서 자세하게 기입해놓지는 않음.

1. Cocoa Framework에서의 기본적인 메모리 관리 룰

a) 생성하는 모든 객체에 대해 소유권을 갖는다.

b) "reatin"을 이용하여 객체의 소유권을 획득 할 수 있다.

c) 더 이상 필요하지 않으면 소유하고 있는 객체의 소유권을 내주어야 한다.

d) 소유하고 있지 않은 객체의 소유권은 내주어선 안 된다.

2. Objective-C 객체의 행동과 메소드 비교

Objective-C 객체에 대한 행동Obejctive-C 메소드
생성, 소유권 획득alloc/new/copy/mutableCopy ...
소유권 획득retain
소유권 포기release
소멸dealloc

주의할점 : release는 어디까지나 retain count를 하나 줄이는것이지 객체를 메모리에서 날리는것이 아니다.

3. 샘플 코드 실행

@interface MyClass : NSObject <NSCopying>
- (id)copyWithZone:(NSZone *)zone;
@end
@implementation MyClass
- (id)copyWithZone:(NSZone *)zone {
    MyClass *newObj = [[self class] allocWithZone:zone];
    return newObj;
}
@end

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"log1: %lu",[[[MyClass alloc] init] retainCount]);
    id myData = [[MyClass alloc] init];
    NSLog(@"log2: %lu",[myData retainCount]);
    [myData retain];
    [myData retain];
    NSLog(@"log3: %lu",[myData retainCount]);
    [myData release];
    NSLog(@"log4: %lu",[myData retainCount]);
    NSLog(@"log5: %lu",[[myData copy] retainCount]);
}

@end

실행결과

2021-03-14 14:04:18.000969+0900 nonARC[37026:313611] log1: 1
2021-03-14 14:04:18.001070+0900 nonARC[37026:313611] log2: 1
2021-03-14 14:04:18.001148+0900 nonARC[37026:313611] log3: 3
2021-03-14 14:04:18.001203+0900 nonARC[37026:313611] log4: 2
2021-03-14 14:04:18.001271+0900 nonARC[37026:313611] log5: 1

샘플코드 링크

4. Autorelease

오토 릴리즈의 작동방식

- (void)mrcAutoReleaseSample {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    id obj = [[NSObject alloc] init];
    [obj autorelease];
    [pool drain]; // pool 안의 객체를 전부 realese시킨다. 즉 [obj relase] 도 실행이 된다.
}

참조: iOS와 OS X의 메모리 관리와 멀티스레딩 기법 - 가즈키 사카모토, 도모히코 후루모토

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함