views:

835

answers:

3

How do I declare a simple string "test" to a variable?

+19  A: 

A C string is just like in C.

char myCString[] = "test";

An NSString uses the @ character:

NSString *myNSString = @"test";

If you need to manage the NSString's memory:

NSString *myNSString = [NSString stringWithFormat:@"test"];
NSString *myRetainedNSString = [[NSString alloc] initWithFormat:@"test"];

Or if you need an editable string:

NSMutableString *myMutableString = [NSMutableString stringWithFormat:@"test"];

You can read more from the Apple NSString documentation.

Carl Norum
What is the different beween NSString and char?
powtac
`char` is a native C type, and `NSString`/`NSMutableString` are classes for managing strings in Cocoa/Objective-C. They don't really bear much relationship to a normal C string (array of `char`) at all. You should check out some basic "how-to" Objective-C documentation to get started.
Carl Norum
+6  A: 

NSString *testString = @"test";

Jeff Kelley
That was the answer I was looking for. Although the answer the Carl Norum is very detailed.
powtac
+5  A: 

In addition to the basic allocation there are a whole lot of methods you get when using the NSString Class that you don't get with the Standard Char[] array. That is why Objective programming is better!

For instance filling a string with the contents of a html webpage, with a single line of code!**

Creating and Initializing Strings

+ string
– init
– initWithBytes:length:encoding:
– initWithBytesNoCopy:length:encoding:freeWhenDone:
– initWithCharacters:length:
– initWithCharactersNoCopy:length:freeWhenDone:
– initWithString:
– initWithCString:encoding:
– initWithUTF8String:
– initWithFormat:
– initWithFormat:arguments:
– initWithFormat:locale:
– initWithFormat:locale:arguments:
– initWithData:encoding:
+ stringWithFormat:
+ localizedStringWithFormat:
+ stringWithCharacters:length:
+ stringWithString:
+ stringWithCString:encoding:
+ stringWithUTF8String:

Creating and Initializing a String from a File

+ stringWithContentsOfFile:encoding:error:
– initWithContentsOfFile:encoding:error:
+ stringWithContentsOfFile:usedEncoding:error:
– initWithContentsOfFile:usedEncoding:error:

Creating and Initializing a String from an URL

+ stringWithContentsOfURL:encoding:error:
– initWithContentsOfURL:encoding:error:
+ stringWithContentsOfURL:usedEncoding:error:
– initWithContentsOfURL:usedEncoding:error:
Tony Lambert