CodeGuy
CodeGuy

Reputation: 28907

Objective-C returning an array - memory problems

I'd like to return an NSMutableArray with three objects. Here's what I've got:

NSMutableArray *output = [[NSMutableArray alloc] init];
NSString *a = [[NSString alloc] initWithFormat:@"%i",aa];
NSString *b = [[NSString alloc] initWithFormat:@"%i",bb];
NSString *c = [[NSString alloc] initWithFormat:@"%i",cc];

[output addObject:a];
[output addObject:b];
[output addObject:c];

return output;

But I'm getting memory leaks. What is wrong?

Upvotes: 1

Views: 504

Answers (5)

endo.anaconda
endo.anaconda

Reputation: 2468

1st Issue:

Try it that way, then the NSString will get released. [NSString stringWithFormat:@"%@", aa]; keep also an eye on the format-placeholders:

  • %i for Int
  • %d for other numbers
  • %@ for Strings and many more objects.

2nd Issue:

and do an autorelease with your output var, because the last action in the function is the reset.

NSMutableArray *output = [[[NSMutableArray alloc] init] autorelease];

complete snippet:

NSMutableArray *output = [[[NSMutableArray alloc] init] autorelease];
NSString *a = [NSString stringWithFormat:@"%@", aa];
NSString *b = [NSString stringWithFormat:@"%@", bb];
NSString *c = [NSString stringWithFormat:@"%@", cc];


[output addObject:a];
[output addObject:b];
[output addObject:c];

return output;

cheers endo

Upvotes: 4

Ishu
Ishu

Reputation: 12787

use this

NSMutableArray *output = [NSMutableArray array];
NSString *a = [NSString stringWithFormat:@"%i",aa];
NSString *b = [[NSString stringWithFormat:@"%i",bb];
NSString *c = [[NSString stringWithFormat:@"%i",cc];

[output addObject:a];
[output addObject:b];
[output addObject:c];

return output;

here no leaks, you are having leak in array as well as strings.

Upvotes: 2

Robin
Robin

Reputation: 10011

You need to release the objects of type NSString after adding them to the output variable and then autorelease output before returning it

Upvotes: 0

Schultz9999
Schultz9999

Reputation: 8926

How do you know you have memory leaks? If the Analyzer reports you that then it's probably because you are returning the array that is not marked for autorelease. So it depends on what you do outside this method. You may need to either:

...
return [output autorelease];
...

Or:

NSArray *a = [[self createArray] autorelease];

Also you're allocating string and put them into array. However that makes the retain count of strings 2. You need to autorelease them too. Or rather use [NSString stringWithFormat...] static initializer.

Upvotes: 0

donkim
donkim

Reputation: 13137

You'll want to return it with an autorelease on it. Like this:

NSMutableArray *output = [[[NSMutableArray alloc] init] autorelease];

Upvotes: 1

Related Questions