简体   繁体   English

这两种创建NSStrings的方法有什么区别?

[英]What is the difference between these two ways of creating NSStrings?

  1. NSString *myString = @"Hello";

  2. 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. 我知道使用方法(1)创建一个指向字符串文字的指针,该字符串文字被定义为静态内存(并且不能被释放),并且使用(2)创建一个将被自动释放的NSString对象。

  • Is using method (1) bad? 使用方法(1)不好吗?
  • What are the major differences? 有哪些主要区别?
  • Is there any instances where you would want to use (1)? 有没有你想要使用的情况(1)?
  • Is there a performance difference? 有性能差异吗?

PS 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. PS我已经在Stack Overflow上进行了广泛的搜索,虽然对同一主题有疑问,但他们都没有回答我上面发布的问题。

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";

So here we just assign myString to the pointer to string literal. 所以这里我们只是将myString分配给指向字符串文字的指针。

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]);

Output: 输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM