首先,抱歉代码量。 我在管理记忆方面做错了什么。我无法理解为什么分析仪会引发内存泄漏。
@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;
}
答案 0 :(得分:2)
[super dealloc]
应该始终是dealloc
方法中的最后一次通话。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];
,然后再执行其余操作,然后无需任何调用即可发布。
答案 1 :(得分: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 numberWithFloat:3.4];
numero = [NSNumber numberWithFloat:5.8];
// Now you don't need to release it at all ;)
//[numero release]; **<-- Leak of memory**
或者您可以通过以下方式修复现有示例:
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**
答案 2 :(得分:1)
在dealloc
方法中,首先尝试发布array
,然后然后调用[super dealloc]
。 (通常在调用超类的dealloc
方法之前,你应该先释放你的ivars。)
答案 3 :(得分:0)
在数组中添加numero之后,你必须释放numero,因为addObject会调用保留在numero上。第二个数字5.8是可以的,因为你不会在它上面调用alloc。