initWithFormat 和stringWithFormat的区别
来源:互联网 发布:java变量命名规则 编辑:程序博客网 时间:2024/05/22 10:33
差别:
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 做初步的搜检.
- initWithFormat 和stringWithFormat的区别
- initWithFormat与initWithString的区别、initWithFormat与stringWithFormat的区别
- MRC下的 initWithFormat: 和 stringWithFormat:
- stringWithFormat与[NSString alloc]initWithFormat 区别
- [iOS] stringWithFormat 和 initWithFormat 有何不同?
- iOS stringWithFormat 和 initWithFormat 有何不同?
- [iOS] stringWithFormat 和 initWithFormat 有何不同?
- NSString中initWithString和initWithFormat的区别
- ios:initWithString和initWithFormat的区别
- OC学习:快速初始化 、 stringWithString 和 stringWithFormat的区别
- iOS: NSString应该用initWithFormat? 还是 stringWithFormat?
- NSString应该用initWithFormat? 还是 stringWithFormat?
- stringWithFormat和stringWithString有什么区别
- objective-C: NSString应该用initWithFormat? 还是 stringWithFormat?
- objective-C: NSString应当用initWithFormat? 还是 stringWithFormat?
- Objective-C NSString应该用initWithFormat? 还是 stringWithFormat?
- objective-C: NSString应该用initWithFormat? 还是 stringWithFormat?
- objective-C: NSString应该用initWithFormat? 还是 stringWithFormat?
- 查看浏览器内核版本
- 系统下载网址
- Eclipse快捷键 10个最有用的快捷键
- Compiler_C++混合编程
- Classic Shell:找回 Windows 8 / Windows Server 2012 的经典的开始按钮和开始菜单
- initWithFormat 和stringWithFormat的区别
- PowerBuilder通过ODBC和JBDC连接mysql数据库
- C++函数式编程(五)性能影响
- 给对话框添加状态栏
- 裸板开发--makefile 出错问题解决
- Eclipse快捷键大全(转载)
- access数据库中小数点前0没有了
- Qt字符串和java字符串的split方法比较和python的解析比较
- [程序猿感悟] 好的程序员应该掌握的几门编程语言