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

风流意气都作罢 提交于 2020-01-13 17:12:12

问题


  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.

  • 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.


回答1:


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.

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


来源:https://stackoverflow.com/questions/3052499/what-is-the-difference-between-these-two-ways-of-creating-nsstrings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!