2012-06-26 3 views
0

명령 줄 응용 프로그램에서 두 클래스 (FirstClass 및 SecondClass)를 만들었습니다. FirstClass 메서드에서 SecondClass 객체를 만들었습니다. 이제 main에서이 메소드를 호출하고 해당 객체에 할당 된 메모리를 해제하려고합니다. 다음과 같이 내 코드는 내가 대한 합성 속성을 가정하고클래스에서 다른 클래스의 객체를 해제하는 방법은 무엇입니까?

int main (int argc, const char * argv[]) { 

@autoreleasepool { 

    // insert code here... 
    // NSLog(@"Hello, World!"); 

    NSMutableArray *arrayMain = [[NSMutableArray alloc]init]; 

    arrayMain = [FirstClass addObject]; 

    for (int i = 0; i<[arrayMain count]; i++) { 

     NSLog(@"%@",[[arrayMain objectAtIndex:i] name]); 
    } 

    NSLog(@"%ld",[arrayMain retainCount]); 

} 
return 0; 
} 
+0

한 번 봐, retainCount는 쓸모가 왜 수많은 이유 중 0 하나를 반환 할 수 없습니다. – bbum

답변

0

.. 다음과 같이

내가 제로로 카운트를 유지하게 할
@implementation FirstClass 

+(NSMutableArray *) addObject{ 
    NSMutableArray *namesArray = [[[NSMutableArray alloc]init] autorelease]; 
    SecondClass *second = [[SecondClass alloc]init]; 
    NSLog(@"Before adding object, count = %ld ",[second retainCount]); //RC = 1 
    [second setName:@"Mobicule"]; 
    [namesArray addObject:second]; 
    NSLog(@"First object addeded, count = %ld ",[second retainCount]); //RC = 2 
    [second release]; 
    NSLog(@"After release, count = %ld",[second retainCount]); //RC = 1 
    return namesArray; 
} 

@end 

..

그리고 주요 기능은 ...입니다 이름은 retain입니다. 그것은 결코 당신에게 아무것도 유용 를 알 수 없기 때문에

+(NSMutableArray *) addObject{ 
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
    NSMutableArray *namesArray = [[NSMutableArray alloc]init]; 
    SecondClass *second = [[[SecondClass alloc]init]autorelease]; 
    NSLog(@"Before adding object, count = %ld ",[second retainCount]); //RC = 1 
    [second setName:@"Mobicule"]; //implementation will handle the release for you 
    [namesArray addObject:second]; 
    NSLog(@"First object addeded, count = %ld ",[second retainCount]); //RC = 2 
    [pool release]; 
    NSLog(@"After pool release, count = %ld",[second retainCount]); //RC=1 
    return [namesArray autorelease]; 
} 

당신은 -retainCount를 사용해서는 안됩니다.

하는 것은 정의에 When to use -retainCount?

관련 문제