// Manager.m
@implementation Manager
-(void) startDraw{
Rectangle *rect = [[Rectangle alloc]init];
[rect setDelegate:self]; // RectangleProtocol 을 따라야 함.
[rect draw];
}
-(void) testMethod{
NSLog(@"Test Method.");
}
-(Shape*) getNewShape{
Shape *newShape = [[Shape alloc]init];
return newShape;
}
@end
// main.m
#import <Foundation/Foundation.h>
#import "Manager.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Manager *manager = [[Manager alloc]init];
[manager startDraw];
Shape* newShape = [manager getNewShape];
}
return 0;
}
메모리 관리를 수동으로 하면서 위의 코드 처럼 Shape* 객체를 하나 함수 호출로 받아왔다.
이 객체의 메모리 해제 시점(release)은 언제로 하는게 좋을까??
1. 일반적인 메모리 해제 수순
return 하기 전에 해제해 버린다??
-(Shape*) getNewShape{
Shape *newShape = [[Shape alloc]init];
[newShape release]
return newShape;
}
그럼 이 함수를 호출하는 입장에서는 nil 만 받게 될거다.
2.(solution) autorelease 이용
-(Shape*) getNewShape{
Shape *newShape = [[Shape alloc]init];
return [newShape autorelease];
}
이렇게 return 하기 전에 autorelease 메시지를 호출 해 주게 되면,
외부에서 사용할 때 @autoreleasepool 블록 안에서 자유롭게 사용 하다가 블록이 끝나는 시점에 한꺼번에 해제되게 된다.
댓글 없음:
댓글 쓰기