Mac Forums

Mac Forums (http://www.mac-forums.com/forums/)
-   OS X - Development and Darwin (http://www.mac-forums.com/forums/os-x-development-darwin/)
-   -   Which of these two ways are the best NSString Initializer ? (http://www.mac-forums.com/forums/os-x-development-darwin/170662-these-two-ways-best-nsstring-initializer.html)

Bracer 10-08-2009 05:49 AM

Which of these two ways are the best NSString Initializer ?
 
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

wmprice1240 10-08-2009 07:34 AM

Quote:

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.

Quote:

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.

Bracer 10-08-2009 08:02 AM

Thank you :)

xstep 10-08-2009 03:10 PM

Bracer, you may want to review Introduction to The Objective-C 2.0 Programming Language


All times are GMT -4. The time now is 03:15 PM.

Powered by vBulletin
Copyright ©2000 - 2014, Jelsoft Enterprises Ltd.