开发者

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 st开发者_如何学编程atement, we should call autorelease. But I want to know, what is happening in the stringWithFormat:method. How it is returning NSString.

Thanks.


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.


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.


You should retain:

[[self getArray] retain];

Or return non-autoreleased object in getArray.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜