NSString的一点tips

本文讨论了在Objective-C中管理NSString实例的正确方法,特别是在从SQLite数据库读取数据并将其添加到NSMutableArray时。文章解释了使用不同字符串创建方法的区别,并提供了一个示例来展示如何正确地分配和释放内存。

I have the following method

   -(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;
   
}

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?

link | improve this question


A note regarding method naming: In Cocoa, a method named “getFoo” returns foo by reference: - (void) getFoo:(out NSMutableArray **)outArray. To be consistent with Cocoa naming conventions, you should name your method simply “paises”. – Peter Hosey Mar 2 '09 at 18:13
feedback

2 Answers

up vote  6  down vote accepted

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;
}

In summary:

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

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

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

link | improve this answer


Thanks a lot. I'm releasing the NSMutableArray manually, but the autorelease is a better option. Gonna change it. – Sacha Fuentes Mar 2 '09 at 14:30
feedback

stringWithUTF8String: returns an autorelease string which will be released automatically by Cocoa in the next eventloop. But the string is also retained in the array when you do addObject:...so as long as it is in the array it will be retained.

link | improve this answer

Was this post useful to you?     
欢迎加群互相学习,共同进步。QQ群:iOS: 58099570 | Android: 330987132 | Go:217696290 | Python:336880185 | 做人要厚道,转载请注明出处!http://www.cnblogs.com/sunshine-anycall/archive/2011/10/21/2219738.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值