2011-12-15 45 views
1

首先,對於代碼量,感到抱歉。 我在做什麼錯誤管理內存。我不明白爲什麼分析器會引發內存泄漏。簡單示例代碼中的內存泄漏

@interface obj : NSObject 
{ 
    NSMutableArray *array; 
} 
@property (retain, nonatomic) NSMutableArray *array; 
@end 

@implementation obj 
@synthesize array; 

- (id)init 
{ 
    self = [super init]; 
    if (self) 
    { 
     // Initialization code here. 
     array = [[NSMutableArray alloc] init]; 
    } 

    return self; 
} 

- (void)dealloc 
{ 
    [super dealloc]; 
    [array release]; 
} 

@end 

int main (int argc, const char * argv[]) 
{ 
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 

    // insert code here... 
    obj *test = [[obj alloc] init]; 
    NSNumber *numero = [[NSNumber alloc] initWithFloat:3.4]; 

    NSLog(@"Número: %g \n", [numero floatValue]); 

    [test.array addObject:numero]; 

    NSLog(@"Numero de elementos: %lu", [test.array count]); 

    NSLog(@"Valor: %g", [[test.array objectAtIndex:0] floatValue]); 

    NSLog(@"Numero de elementos t2: %lu", [test.array count]); 

    numero = [NSNumber numberWithFloat:5.8]; 

    NSLog(@"Valor t2: %g", [[test.array objectAtIndex:0] floatValue]); 
    NSLog(@"Número t2: %g \n", [numero floatValue]); 

    [test.array addObject:numero];  

    NSLog(@"Valor: %g", [[test.array objectAtIndex:0] floatValue]); 

    [numero release]; **<-- Leak of memory** 
    [test release]; 
    [pool drain]; 

    return 0; 
} 

回答

2

簡單修復,您在重新分配它之前忘記釋放現有值。

// You created an instance of NSNumber here 
NSNumber *numero = [[NSNumber alloc] initWithFloat:3.4]; 

// Then you reassigned it here without releasing it first which caused the leak HERE 
numero = [NSNumber numberWithFloat:5.8]; 

[numero release]; **<-- Leak of memory** 

您可以完全由它返回一個自動釋放的對象這兩種情況下使用numberWithFloat解決這個問題。

NSNumber *numero = [[NSNumber alloc] initWithFloat:3.4]; 

[numero release]; 

numero = [NSNumber numberWithFloat:5.8]; 

// Remove this one since numberWithFloat returns an autoreleased object 
//[numero release]; **<-- Leak of memory** 
+0

感謝您的幫助和很好的解釋:

NSNumber *numero = [NSNumber numberWithFloat:3.4]; numero = [NSNumber numberWithFloat:5.8]; // Now you don't need to release it at all ;) //[numero release]; **<-- Leak of memory** 

或者您也可以通過修復現有的例子。我不知道humberWithFloat的方法是自動發佈的。 – 2011-12-15 22:01:54

1

在你dealloc方法,嘗試釋放array第一和然後調用[super dealloc]。 (正常情況下你應該首先釋放你的高德,調用父類的方法dealloc前。)

2
  1. [super dealloc]應始終是在dealloc方法的最後一次通話。
  2. 無論您何時分配一個變量來引用您擁有所有權(例如調用alloc/init的結果),您必須在重新分配它之前釋放它。

NSNumber *numero = [[NSNumber alloc] initWithFloat:3.4]; 
... 
[numero release]; //You must call release before reassigning 
numero = [NSNumber numberWithFloat:5.8]; 
... 
[numero release]; //This is bad because it is now assigned an autoreleased value 

現在你比如有沒有需要分配初始numero,只是將其指定爲NSNumber *numero = [NSNumber numberWithFloat:3.4];你做休息,那麼無需任何呼籲釋放。

0

在數組中添加了數字之後,必須釋放數字,因爲addObject調用保留在數字上。第二個數字5.8是可以的,因爲你不會在它上面調用alloc。