2010-06-16 3 views
0

내 응용 프로그램의 상태를 복원하는 코드를 작성했지만 NSMutableArray에 메모리 누수가 있습니다. 나는 Xcode에 익숙하지 않아서 이것이 간과 한 일인가 있다면 사과드립니다. 어떤 도움을 주셔서 감사합니다. 당신이 viewDidUnload에서 nil으로 설정하면 LQRootViewController에서 NSMutableArray를 사용하는 메모리 누수가 App Delegate에서 호출되었습니다.

AppDelegate.m 

- (void)applicationDidFinishLaunching:(UIApplication *)application { 
    [rootViewController restoreState]; 
} 

RootViewController.h 

@interface rootViewController : UIViewController { 
    NSMutableArray *offendingNSMutableArray; 
} 
@property (nonatomic, retain) NSMutableArray *offendingNSMutableArray; 

RootViewController.m 

@synthesize offendingNSMutableArray; 

- (void)restoreState { 
    // Gets an array stored in the user defaults plist 
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; 
    self.offendingNSMutableArray = [[NSMutableArray alloc]  
      initWithArray:[userDefaults objectForKey:kArrayValue]]; 
} 

- (void)viewDidUnload { 
    self.offendingNSMutableArray = nil; 
} 

- (void)dealloc { 
    [offendingNSMutableArray release]; 
} 
+1

우선, retainCount = 1로 alloc-init을 수행 한 다음 setOffendingNSMutableArray : -> retainCount = 2를 수행하십시오. viewDidUnload에서 nil로 설정하므로 retainCount = 1이고 배열에 대한 포인터를 잃어 버리고 있습니다. 너 누출이야. – beefon

+0

미안 해요. 나는 init을 할당하지 않고 다음 줄의 코드를 사용하여 동일한 줄에 설정합니다 : self.offendingNSMutableArray = [[NSMutableArray alloc] initWithArray : [userDefaults objectForKey : kArrayValue] ]; –

답변

0

, 당신은 무엇을 dealloc에 출시 예정? 당신은 단지 dealloc에서

self.offendingNSMutableArray = nil; 

해야한다, 그 유지 속성에 대한 일반적인 방법입니다.

편집 : 위의 의견에서 지금 확인하십시오. alloc/init을 할 때 autorelease가 필요하다. 속성 설정자는 보유합니다.

+0

인스 트루먼츠를 사용합니다. 누출 된 개체 : alloc 초기화 줄의 Malloc 32 바이트와 누출 된 개체 : NSCFArray를 할당 초기화 줄에 표시하고 있습니다. –

+0

'dealloc'에있는 속성 설정자를 호출하는 것이 나쁜 생각 인 것으로 알려졌습니다. 이는 중도 해적판에서 원치 않는 알림이 실행될 수 있기 때문입니다. 기억 누출에 관해서는 - 분명히 하나이다. @ beefon의 코멘트를 보라. – walkytalky

+0

@walkytalky 이것이 http://developer.apple.com/mac/library/documentation/cocoa/conceptual/objectivec/articles/ocProperties.html에서 권장되는 내용입니다. 예, 지금은 누수가 나타납니다. – unbeli

0

OK, 그래서 오토 릴리즈 추가하여 누수를 해결할 것 같습니다 :

- (void)restoreState { 
    // Gets an array stored in the user defaults plist 
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; 
    self.offendingNSMutableArray = [[[NSMutableArray alloc]  
     initWithArray:[userDefaults objectForKey:kArrayValue]] autorelease]; 
} 

을하지만 내가 응용 프로그램의 다른 곳에서 offendingNSMutableArray 참조 때문에 오토 릴리즈를 사용하지 않았다 생각?

+0

세터는 객체를 자체적으로 '보유'합니다. 이'autorelease'는'alloc'을 통해 얻은 로컬 소유권을 포기합니다. 그것을 한 줄에 모두 넣으면 의미가 약간 불투명해진다. 한 줄에'alloc' /'init'을 넣으면 더 명확 해지며, 두 번째로 할당하고, 세 번째에 명시 적으로'release'를 할당한다. 최종 결과는 (거의) 동일합니다. – walkytalky

관련 문제