Multiple declarations and initialization of NSString

I am new to ios development. I checked NSString and found that it was redundant using several methods that are under

1) NSString *theString = @"hello";

2) NSString *string1 = [NSString stringWithString:@"This is"];

3) NSString *string =[[NSString alloc]init]; string =@"Hello";

Now I am confused above the three and would like to know the difference between the two?

+3
source share
3 answers

Yes, all three ways to create a string ... I'm trying to explain to you one by one.

Do you think you have to remember that the string Objective-c presented @"". all that comes in double quotes is a string, for example, @"Hello"is string. @""is basically a literal to create NSString.

  • NSString *theString = @"hello";

EDIT:

NSString. Objective-C .

2. NSString *string1 = [NSString stringWithString:@"This is"];

autorelease NSString, - -diff. . NSString autorelease NSString. stringWithString, NSString Object, , NSString .

3. NSString *string =[[NSString alloc]init];
             string =@"Hello";

, NSString, , ( -ARC), . 1, Object. , memory-leak (In -ARC), strong > .

+2

1) 2) . . [NSString stringWithString: str] str, str .

3) NSString. , "=", 1) NSString. NSString 3), , :

NSString *string =[[NSString alloc]init];
printf("\n string_1-> = %p\n", string );
string = @"Hello";
printf("\n string_2-> = %p\n", string );
+1

, @"blah" Objective-C NSString. is NSString.

, . NSString *string string = <something>.

...

  • . Objective-C.

  • This adds a bit of redundancy, and you would not use it like that. You could use it with a substring or something from another string. As you, you are essentially creating two objects here. The first is [NSString stringWithString:<>];, and the second is @"This is".

  • It's a bit strange. First, an empty string is created @"", and then you replace that string with @"Hello". Do not do that. Pointlessly. You can also just do number 1 because the result is the same.

All three will work, but in these exact cases you will be better off using the first.

0
source

All Articles