How to declare a string in Objective-C?
Ho开发者_如何学编程w do I declare a simple string "test" to a variable?
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.
NSString *testString = @"test";
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
精彩评论