Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple NSString declaration and initialization

I am new to the ios development.I was checking the NSString and where I had found out that it was excessed using the multiple ways which is as under

1) NSString *theString = @"hello";

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

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

Now I am confused with above three and would like to know the differences between then?

like image 272
Sam Avatar asked Jun 10 '26 07:06

Sam


1 Answers

Yes all three are ways to create string...I try to explain you one by one.

One think you must remember that in Objective-c string is represented by @"". whatever comes double quotes is string eg @"Hello" is string. @"" is basically literal to create NSString.

  1. NSString *theString = @"hello";

EDIT:

In this statement we are creating an NSString constant. Objective-C string constant is created at compile time and exists throughout your program’s execution.

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

In this statement again, we are creating an autorelease object of NSString, but here a slide diff. than the first case. here we are using another NSString object to create a new autorelease object of NSString. So generally we use stringWithString method when we already have NSString Object and we want another NSString object with similar content.

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

Here, In first statement you are creating a NSString Object that you owned and it is your responsibility to release it (In non-ARC code), once you done with this object. Second statement is similar to case 1, by string literal you are creating string Object. but when you put these two statements together it causes you memory-leak(In non-ARC code), because in statement one you are allocating & initiating memory for new string object and right after in second statement you are again assigning a new string object to the same string reference.

like image 59
Suryakant Sharma Avatar answered Jun 11 '26 21:06

Suryakant Sharma