현재 복합 개체 사용법을 배우고 있으며 몇 가지 질문이 있습니다.목표 C에서 복합 오브젝트 구성?
왜 복합 개체를 사용해야합니까? 인스턴스를 사용하려는 클래스가 있지만 완전히 다른 메소드가있는 경우에만 사용합니까?
Rectangle 클래스에서 Square 클래스를 만들고 싶습니다. (저는 Shape라고 부릅니다.) 그러나 Shape 클래스 내에서 initWithHeight : andWidth :를 사용할 계획이 아닙니다. 즉, Square 헤더를 이렇게 선언 할 것입니다. 헤더 파일 구현으로
@interface Square : NSObject { Shape *square; } - (Square*) initWithSide: (int) s; - (void) setSide: (int) s; - (int) side; - (int) area; - (int) perimeter; - (id) free; @end
와
@implementation Square
- (Square*) initWithSide: (int) s
{
if(self = [super init])
{
square = [[Shape alloc] initWithHeight:s andWidth:s];
}
return self;
}
- (void) setSide: (int) s
{
[square setHeight:s];
[square setWidth:s];
}
- (int) side
{
return [square width];
}
- (int) area
{
return [square width]*[square height];
}
- (int) perimeter
{
return 2*([square width]+[square height]);
}
- (id) free
{
[square release];
return square;
}
@end
질문 : 나는 그것을 수정하고 있는가? 내가 작성한 코드가 다소 이상하다고 생각하기 때문에 복합 객체를 구조화하는 데 더 좋은 방법이나 더 좋은 방법이 있습니까? 특히 메모리 할당을 해제하는 방법. 메인 파일에 [mySquare release]가 있기 때문에 [mySquare release] 이전에 [mySquare free]가 먼저 필요합니다. 메모리 할당을 모두 해제하려면 [mySquare release] 만 호출하면됩니다.
-init에서 테스트를 수행하지 않으면 어떻게됩니까? 자유로운 방법이 잘못 되었다면, "사각형"인스턴스에 대한 메모리 할당을 해제하는 더 좋고 올바른 방법은 무엇입니까? – sayzlim
@Sayz Lim : 테스트를 수행하지 않으면 인스턴스 객체가없는 래퍼 객체 만 있습니다. 모든 것이 0/nil을 반환합니다. dealloc 메서드에서 인스턴스 변수를 해제합니다 (update 참조). – JeremyP
@JeremyP dealloc 메소드를 덮어 썼기 때문에, 객체가 더 이상 사용되지 않을 때 release 메소드는 덮어 쓰기 된 dealloc 메소드를 호출 할 것입니다. 덮어 쓴 dealloc은 사각형을 먼저 풀어 주며, 나중에 주 파일에서 생성 된 인스턴스 인 dealloc을 해제합니다. – sayzlim