0

我是否通过以下方式创建多个内存泄漏:

NSMutableArray *array=[[NSMutableArray alloc] init];
[array addObject:[[NSNumber alloc] initWithBool:boolVariable1]];
[array addObject:[[NSNumber alloc] initWithBool:boolVariable2]];
[array addObject:[[NSNumber alloc] initWithInt:intVariable]];
[array addObject:[[NSNumber alloc] initWithFloat:floatVariable]];
[array writeToFile:[self dataFilePath] atomically:YES];
[array release];

是否更好地使用:

[array addObject:[NSNumber numberWithInt:intVariable]];
4

2 回答 2

5

规则很简单:每次调用alloc/ new/ copy*/retain时,都必须通过调用 / 来平衡它,auto-否则release就会发生内存泄漏。在代码示例中,你发送allocNSNumber四次,但没有对应的发布,所以这四个NSNumbers会泄漏。

numberWithInt:is not new, alloc,retain并且不以 开头copy,因此不需要通过调用auto-/来平衡它release

您还可以使用一些不同的工具来查找内存泄漏,例如Instruments

于 2010-11-18T17:18:51.570 回答
2

呼吁

[NSNumber numberWithInt:intVariable]

在概念上等同于

[[[NSNumber alloc] initWithInt:intVariable] autorelease]

所以是的,在你给出的例子中,使用起来会更简单-numberWithInt:

NSMutableArray *array=[[NSMutableArray alloc] init];
[array addObject:[NSNumber numberWithBool:boolVariable1]];
[array addObject:[NSNumber numberWithWithBool:boolVariable2]];
[array addObject:[NSNumber numberWithInt:intVariable]];
[array addObject:[NSNumber numberWithFloat:floatVariable]];
[array writeToFile:[self dataFilePath] atomically:YES];
[array release];

否则,您需要-autorelease在传递给数组的每个参数上添加一个调用。

于 2010-11-18T17:35:42.403 回答