2011-12-15 39 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。