powtac
powtac

Reputation: 41050

How to declare a string in Objective-C?

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

Upvotes: 31

Views: 50739

Answers (3)

AnthonyLambert
AnthonyLambert

Reputation: 8830

Standard string assignment can be done like so:

NSString *myTestString = @"abc123";

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:

If you need a string where you can edit its buffer you want to look at:

NSMutableString

Upvotes: 12

Jeff Kelley
Jeff Kelley

Reputation: 19071

NSString *testString = @"test";

Upvotes: 46

Carl Norum
Carl Norum

Reputation: 224944

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.

Upvotes: 50

Related Questions