Which of these two ways are the best NSString Initializer ?

Joined
Oct 7, 2009
Messages
14
Reaction score
0
Points
1
Location
Singapore
What is the "correct"way of declaring NSString ?

Code:
-(void) PrintMessage
{
	NSString* Variable1 = [[NSString alloc] initWithCString: "This is Variable 1 String." ];
	NSString* Variable2 = @"This is Variable 2 String.";
	
	NSLog(@"\n\n%@\n%@",Variable1,Variable2 );
}

I also realize this works:
Code:
id Variable1 = [[NSString alloc] initWithCString: "This is Variable 1 String." ];
id Variable2 = @"This is Variable 2 String.";
	
NSLog(@"\n\n%@\n%@\n\n",Variable1,Variable2 );
printf("\nThis is \"printf\" in action: \n%s\n%s\n",[Variable1 cString],[Variable2 cString]);
"id" is so amazing ! It's like the "Object" or "[]" in Actionscript 3 or the Variant type in Visual Basic !
I am very surprise that Variable2 just "knows" that it's a NSString, I figure it's smart enough to know that when the value assigns to it is of NSString type and it convert itself automatically, absolute brilliant from my point of view ;p
 
Joined
May 2, 2009
Messages
480
Reaction score
13
Points
18
Your Mac's Specs
MBP 2.33 4GB: MacPro 8 Core 2.8, 16GB: MacMini 2.26 4GB: MacMin 2.53 4GB: iPhone3GS 32GB
NSString* Variable2 = @"This is Variable 2 String.";

This would be considered the 'correct' form, though both forms accomplish the same thing. The first approach is simply too verbose and the initializer provides nothing beyond what the direct initialization accomplishes.

I am very surprise that Variable2 just "knows" that it's a NSString, I figure it's smart enough to know that when the value assigns to it is of NSString type and it convert itself automatically

Actually, the language itself helps here. The '@' token essentially allows the compiler to do the necessary conversion from the character string to the NSString.
 

Shop Amazon


Shop for your Apple, Mac, iPhone and other computer products on Amazon.
We are a participant in the Amazon Services LLC Associates Program, an affiliate program designed to provide a means for us to earn fees by linking to Amazon and affiliated sites.
Top