Pet*_*mer 0 memory-leaks objective-c nsnumber alloc
我是否通过以下方式创建多个内存泄漏:
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];
Run Code Online (Sandbox Code Playgroud)
使用起来更好:
[array addObject:[NSNumber numberWithInt:intVariable]];
Run Code Online (Sandbox Code Playgroud)
该规则很简单:每次通话时间alloc
/ new
/ copy*
/ retain
,你必须要在通话平衡它auto-
/ release
,否则你已经内存泄漏.在代码示例中,您发送alloc
了NSNumber
四次,但没有相应的版本,因此四个NSNumber
s将泄漏.
numberWithInt:
不new
,alloc
,retain
并且不下手copy
,所以它并不需要用一个呼叫来平衡auto-
/ release
.
您还可以使用一些不同的工具来查找内存泄漏,例如Instruments.