开发者

NSMutableString memory management get me confused

I am learning Objective-C right now, however, there is memory management puzzle here make me so confused.

Let me see, within one method, I create a NSMutableString, and return it.

- (NSMutableString *)methodNameWithParameter:(id)parameter
{
    NSMutableString *string = [NSMutableString stringWithString:@""];
    // do something
    return string; 
}

The question is who is responsible to release this memory, calling or called?

Second example:

- (NSMutableString *)methodNa开发者_运维问答meWithParameter:(id)parameter
{
    NSMutableString *string = [NSMutableString alloc]init] autorelease];
    // do something
    return string; 
}

When memory has been released, it will be released at after return string; or it will be released at call method and there is no reference to it.

The third one:

- (NSMutableString *)methodNameWithParameter:(id)parameter
{
    NSMutableString *string = [NSMutableString alloc]init]];
    // do something
    return string; 
}

This time the calling method need to release this memory, is that right?


If you follow the rule, you allocated memory then you are responsible to release it. 90% of time this will work. Of course there are some exception. But in general it should be good.

In your first example, you don't have to release it because you didn't allocate memory yourself, it's the stringWithString that is responsible (I believe it's doing an auto release)

In your second and third example, you are allocating memory with alloc, thus you have to release the memory once you are done with it.

In you second example, you are using autorelease, it means it the memory allocated will eventually be released. (similar to garbage collection in the Microsoft managed code world).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜