0

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]];
skaffman
  • 398,947
  • 96
  • 818
  • 769
Peter Kramer
  • 231
  • 3
  • 7

2 Answers2

5

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.

outis
  • 75,655
  • 22
  • 151
  • 221
2

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.

jlehr
  • 15,557
  • 5
  • 43
  • 45