Reputation: 28907
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
Reputation: 2468
Try it that way, then the NSString will get released.
[NSString stringWithFormat:@"%@", aa];
keep also an eye on the format-placeholders:
and do an autorelease with your output var, because the last action in the function is the reset.
NSMutableArray *output = [[[NSMutableArray alloc] init] autorelease];
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
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
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
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
Reputation: 13137
You'll want to return it with an autorelease
on it. Like this:
NSMutableArray *output = [[[NSMutableArray alloc] init] autorelease];
Upvotes: 1