开发者

Is a memory leak created by a series of [array addObject:[[NSNumber alloc] initWithBool:someVariable]?];

Do I create multiple memory leaks by:

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开发者_开发问答];

Is it better to use:

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


The rule is simple: every time you call alloc/new/copy*/retain, you must balance it with a call to auto-/release, else you've a memory leak. In the code sample, you send alloc to NSNumber four times, but have no corresponding releases, so the four NSNumbers will leak.

numberWithInt: isn't new, alloc, retain and doesn't start with copy, so it doesn't need to be balanced with a call to auto-/release.

There are also a few different tools you can use to find memory leaks, such as Instruments.


The call to

[NSNumber numberWithInt:intVariable]

is conceptually equivalent to

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

so yes, in the example you gave, it would be simpler to use -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];

Otherwise, you'd need to add a call to -autorelease on each argument passed to the array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜