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