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 做初步的檢查.

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章