这两种创建 NSString 的方式有什么区别?
NSString *myString = @"Hello";
NSString *myString = [ NSString stringWithString:@"Hello"];
我明白使用方法(1)创建一个指向定义为静态内存(并且无法释放)的字符串文字,并且使用 (2) 创建一个将自动释放的 NSString 对象。
- 使用方法(1)不好吗?
- 主要区别是什么?
- 您是否有想要使用 (1) 的情况?
- 有性能差异吗?
PS 我在 Stack Overflow 上进行了广泛的搜索,虽然有关于同一主题的问题,但没有一个能回答我上面发布的问题。
NSString *myString = @"Hello";
NSString *myString = [NSString stringWithString:@"Hello"];
I understand that using method (1) creates a pointer to a string literal that is defined as static memory (and cannot be deallocated) and that using (2) creates an NSString object that will be autoreleased.
- Is using method (1) bad?
- What are the major differences?
- Is there any instances where you would want to use (1)?
- Is there a performance difference?
P.S. I have searched extensively on Stack Overflow and while there are questions on the same topic, none of them have answers to the questions I have posted above.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如这个答案<中指出的< /a> 字符串文字是不可变的字符串对象,并在编译时获取它们的地址 - 因此您不需要在运行时创建同一文字字符串的多个实例。
所以这里我们只是将 myString 分配给字符串文字的指针。
第二行使用便利构造函数创建对象,但当我们在这里处理不可变对象时,它会产生与字符串文字相同的指针值 - 因此您得到与第一个变体相同的结果(尽管可能执行一些额外的方法调用)。
因此,您提到的变体似乎执行相同的操作,但第二个变体也可能执行一些额外的调用。
小样本说明发生了什么:
输出:
As pointed in this answer string literals are immutable string objects and get their address in compile-time - so you don't need to create multiple instances of the same literal string during run-time.
So here we just assign myString to the pointer to string literal.
The second line creates object using convenience constructor, but as we're dealing with immutable objects here it results to the same pointer value to string literal - so you get the same result as in 1st variant (although probably performing some extra methods calls).
So it seems that variants you mentioned do the same, but 2nd one may also perform some extra calls.
Small sample illustrating what happens:
Output: