What is the difference between these two ways to create NSStrings?

  • 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 freed), and that using (2) creates an NSString object that will be auto-implemented.

  • Is using method (1) bad?
  • What are the main differences?
  • Are there any cases when you would like to use (1)?
  • Is there a difference in performance?

PS I searched many times for Qaru and, although there are questions on one topic, none of them answered the questions that I posted above.

+3
source share
1 answer

- .

NSString *myString = @"Hello";

, myString .

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

, , - , 1- (, , ).

, , , , , .

, , :

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
+5

Source: https://habr.com/ru/post/1750268/


All Articles