jfalexvijay
jfalexvijay

Reputation: 3711

About memory management in iPhone

Please clarify the following thing.

Everyone knows that; if we are using alloc, retain, new and etc..., we have to release it. For remaining things, we have to use autorelease. My doubt is;

-(NSArray*)getArray{
    NSArray *array = [[NSArray alloc] initWithObjects:@"1", @"2", @"3", @"4", @"5", nil];
    return [array autorelease];
}
NSArray *arr = [self getArray];
---
---

What we have to do the arr?

EDIT:

NSString *str = [NSString stringWithFormat:@"Welcome..."];

If we are using the above statement, we should call autorelease. But I want to know, what is happening in the stringWithFormat:method. How it is returning NSString.

Thanks.

Upvotes: 0

Views: 104

Answers (4)

Mike Hay
Mike Hay

Reputation: 2856

Your getArray method is returning an NSArray that _will_be_ released when the stack fully unwinds.

In the method where you are calling your getArray method, it is safe to use the NSArray, but if you want to keep it, and use it after your current method returns, you will need to retain the NSArray with [arr retain].

Answer to your new question

Class methods, like [NSString stringWithFormat:] or like [NSURL URLWithString:] return objects that have been autoreleased. This is a convention, a standard practice in UIKit and the Apple frameworks.

Upvotes: 0

csano
csano

Reputation: 13716

You don't have to do anything with arr since you didn't explicitly alloc, copy, new, or retain it in its current scope. It's already been added to the autorelease pool so it'll automatically be cleaned up once you're done with it.

EDIT: In your edited question, [NSString stringWithFormat:] returns an autoreleased string. It's basically doing the same thing as you're doing in your getArray method. It builds a NSString (or related) object and autoreleases it before it's returned.

Upvotes: 1

Nekto
Nekto

Reputation: 17877

You should retain:

[[self getArray] retain];

Or return non-autoreleased object in getArray.

Upvotes: 0

brandon
brandon

Reputation: 374

If you are planning to return the array, go ahead and use the [NSArray arrayWithObjects:@"1", @"2", etc, nil] instead.

You then just need to remember to retain it if you want to hold on to it for longer then the autorelease pool will hold it.

The autorelease pool will give it a retain count of 1, and then automatically decrement it by 1 when the release pool gets called. Without retaining it in the calling function, this object will eventually disappear.

Upvotes: 1

Related Questions