Iphone--内存泄露

[self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"gamebg.png"]]];//给UIView直接设置背景

[NSString stringWithFormat:@"%d",section] intValue]  //string型转化为int型

cell.accessoryType=UITableViewCellAccessoryDetailDisclosureButton;



内存泄漏是指一个系统进程在进行某项工作时,会向系统申请一定数量的内存来完成该工作,在正常情况下,该进程完成了此项工作后,应该将其申请的内存进行释放,以便其它进程后续的使用。

但在某些情况下,这些进程在完成其工作后,无法进行正常的释放内存工作,而是一直占有着其所申请的内存空间。在该进程下次工作时,又重新申请内存空间进行工作。久而久之,这项进程就会占用大量的内存空间,而导致内存不足,出现这种情况一般是由于程序bug导致。

以下是Cisco文档中有关内存泄漏的说明:

A memory leak occurs when a process requests or allocates memory and then forgets to free (de?allocate) the
memory when it is finished with that task. As a result, the memory block is reserved until the router is
reloaded. Over time, more and more memory blocks are allocated by that process until there is no free
memory available. Depending on the severity of the low memory situation at this point, the only option you
may have is to reload the router to get it operational again.


今天在看书上的一段代码时,发现NSString实例化时,有时用的是initWithFormat方法,有时用的是stringWithFormat,到底应该如何选择呢?

区别:

1、initWithFormat是实例方法

只能通过 NSString* str = [[NSString alloc] initWithFormat:@"%@",@"Hello World"] 调用,但是必须手动release来释放内存资源

2、stringWithFormat是类方法

可以直接用 NSString* str = [NSString stringWithFormat:@"%@",@"Hello World"] 调用,内存管理上是autorelease的,不用手动显式release


另外国外有个贴子对此有专门讨论(http://www.iphonedevsdk.com/forum/iphone-sdk-development/29249-nsstring-initwithformat-vs-stringwithformat.html

而且提出了一个常见错误:

label.text = [[NSString alloc] initWithFormat:@"%@",@"abc"];

最后在dealloc中将label给release掉

但是仍然会发生内存泄漏!

原因在于:用label.text = ...时,实际是隐式调用的label的setText方法,这会retain label内部的字符串变量text(哪怕这个字符串的内容跟传进来的字符串内容相同,但系统仍然当成二个不同的字符串对象),所以最后release label时,实际上只释放了label内部的text字符串,但是最初用initWithFormat生成的字符串并未释放,最终造成了泄漏。

解决办法有二个:

1、

NSString * str = [[NSString alloc] initWithFormat:@"%@",@"abc"];

label.text = str;

[str release]

最后在dealloc中再[label release]

2、

label.text = [NSString stringWithFormat:@"%@",@"abc"];

然后剩下的事情交给NSAutoreleasePool

最后,如果你不确定你的代码是否有内存泄漏问题,可以用Xcode中的Build-->Build And Analyze 做初步的检查.

 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值