0
votes

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.

4
It's actually really import to show us the rest of the code where arr would be used. If it's all in the same method where you call getArray, then you don't have to do anything at all.Mike Hay
As a side note, according to the naming conventions the prefix "get" is used only for methods that return objects indirectly.albertamg
I added an answer to your question about [NSString stringWithFormat:] below.Mike Hay

4 Answers

1
votes

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.

1
votes

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.

0
votes

You should retain:

[[self getArray] retain];

Or return non-autoreleased object in getArray.

0
votes

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.