这两种创建NSString的方式有什么区别? [英] What is the difference between these two ways of creating NSStrings?

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

问题描述

  1. NSString *myString = @"Hello";

NSString *myString = [NSString stringWithString:@"Hello"];

我了解到,使用方法(1)创建指向定义为静态内存(并且无法释放)的字符串文字的指针,并且使用(2)创建将自动释放的NSString对象.

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.

  • 使用方法(1)是否不好?
  • 主要区别是什么?
  • 是否存在要使用(1)的实例?
  • 是否存在性能差异?

P.S.我在Stack Overflow上进行了广泛的搜索,尽管有关于同一主题的问题,但没有一个问题能回答我上面发布的问题.

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.

推荐答案

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.

NSString *myString = @"Hello";

所以在这里,我们仅将myString分配给字符串文字的指针.

So here we just assign myString to the pointer to string literal.

NSString *myString = [NSString stringWithString:@"Hello"];

第二行使用便利构造函数创建对象,但是由于我们在这里处理不可变对象,因此它得到的字符串文字的指针值相同-因此,您得到的结果与第一个变体相同(尽管可能执行一些额外的方法电话).

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:

NSString* tString = @"lala";
NSString* tString2 = @"lala";   
NSString* tString3 = [NSString stringWithString:@"lala"];
NSString* tString4 = [NSString stringWithFormat:@"%@", @"lala"];

NSLog(@"%p %d", tString, [tString retainCount]);
NSLog(@"%p %d", tString2, [tString2 retainCount]);
NSLog(@"%p %d", tString3, [tString3 retainCount]);
NSLog(@"%p %d", tString4, [tString4 retainCount]);

输出:

 0xd0418 2147483647
 0xd0418 2147483647
 0xd0418 2147483647
 0x50280e0 1

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

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