何时在iPhone中发布NSString [英] When to release a NSString in iPhone

查看:110
本文介绍了何时在iPhone中发布NSString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法

   -(NSMutableArray *) getPaises {
     NSMutableArray * paises;
     paises = [[NSMutableArray alloc] init];
     while( get new row ) {
      NSString *aPais =  [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
      [paises addObject:aPais];
     }
     return paises;
    }

我不是发布aPais,因为如果我做的应用程序崩溃。我不知道什么时候或者是否应该在使用后在某处释放它,如果是,我该怎么做。只是释放NSMutableArray就够了?或者我必须遍历它并释放每个对象吗?

I am not releasing the aPais, because if I do it the application crashes. I don't know when or if whether I should release it somewhere after using it and, if so, how do I do it. Just release the NSMutableArray is enough? Or do I have to traverse it and release each object?

如果我不需要释放它,谁是负责释放?

And if I don't have to release it, who is the responsible for releasing?

推荐答案

如epatel所说,你不需要释放那个特定的字符串。如果你想更积极主动,你可以这样做:

As epatel said, you don't need to release that particular string. If you wanted to be more proactive, you could do this instead:

-(NSMutableArray *) getPaises {
    NSMutableArray * paises;
    paises = [[[NSMutableArray alloc] init] autorelease];
    while( get new row ) {
        NSString *aPais =  [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
        [paises addObject:aPais];
        [aPais release];
    }
    return paises;
}

总结:


  • [[NSString alloc] initWith ...] - >您必须释放或自动释放。

  • [[NSString alloc] initWith...] -> You must release or autorelease.

[NSString

[NSString stringWith...] -> No need to release.

- 编辑:添加 autorelease 为paises,因为你正在返回它。当你返回一个对象,总是自动释放它,如果你有alloc& init'd它。

-- Added autorelease for paises, as you are returning it. When you return an object, always autorelease it if you have alloc&init'd it.

这篇关于何时在iPhone中发布NSString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆