1

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?

1
  • You'll want to mark output for autorelease. Commented Jan 11, 2011 at 5:36

5 Answers 5

4

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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

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

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.