initWithFormat 和stringWithFormat的區別
差別:
1、initWithFormat是實例辦法
隻能經由過程 NSString* str = [[NSString alloc] initWithFormat:@"%@",@"Hello World"] 調用,然則必須手動release來開釋內存資料
2、stringWithFormat是類辦法
可以直接用 NSString* str = [NSString stringWithFormat:@"%@",@"Hello World"] 調用,內存經管上是autorelease的,不消手動顯式release
別的國外有個貼子對此有專門評論辯論(https://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 做初步的搜檢.
最後更新:2017-04-04 07:03:36