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
2009-10-14 16:50:17
What is the different beween NSString and char?
powtac
2009-10-14 16:51:13
`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
2009-10-14 16:55:58
That was the answer I was looking for. Although the answer the Carl Norum is very detailed.
powtac
2009-10-15 13:18:45
+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
2009-10-14 16:57:19