NSString 和 NSMutableString 有什么区别? [英] What is the difference between NSString and NSMutableString?

查看:50
本文介绍了NSString 和 NSMutableString 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要澄清一下 NSString 和 NSMutableString 之间的区别.任何人都可以简单地扩展一下吗?

I need a clarification regarding the difference between the NSString and NSMutableString. Can any one expand briefly?

推荐答案

假设你有这样的代码

NSString *s = [[NSString alloc] initWithString:@"Hello"];

s = [s stringByAppendingString:@"World"];

和其他类似的代码

NSMutableString *ms = [[NSMutableString alloc] initWithString:@"Hello"];

[ms appendString:@"World"];

从功能上讲,这两者都做同样的事情,除了一个区别 - 顶部代码块泄漏.-[NSString stringByAppendingString:] 生成一个新的不可变 NSString 对象,然后你告诉指针 s 指向它.但是,在此过程中,您孤立了 s 最初指向的 NSString 对象.如下更换线路将消除泄漏:

Both of these, functionally, do the same thing except for one difference - the top code block leaks. -[NSString stringByAppendingString:] generates a new immutable NSString object which you then tell the pointer s to point to. In the process, however, you orphan the NSString object that s originally pointed to. Replacing the line as follows would get rid of the leak:

s = [[s autorelease] stringByAppendingString:@"World"];

这篇关于NSString 和 NSMutableString 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆