1.8. Allocating and Making Use of Strings
Problem
You want work with strings in Objective-C
Solution
Use NSString and NSMutableString classes.
Discussion
The NSString and
NSMutableString
classes allow you to store a string of characters in memory. The
NSString class is immutable, meaning that once it is created, its contents
cannot be modified. Mutable strings represented with the NSMutableString can be modified once they
are created. We will see an example of both of these classes very
soon.
Objective-C strings should be placed inside double quotes. The starting double-quote should be
prefixed with an at sign (@). For instance, the sentence Hello, World, represented as a string in
Objective-C, is written like so:
@"Hello, World"
There are various ways of placing a string inside an instance of
NSString or NSMutableString classes. Here is how:
NSString *simpleString = @"This is a simple string"; NSString *anotherString = [NSString stringWithString:@"This is another simple string"]; NSString *oneMorestring = [[NSString alloc] initWithString:@"One more!"]; NSMutableString *mutableOne = [NSMutableString stringWithString:@"Mutable String"]; NSMutableString *anotherMutableOne = [[NSMutableString alloc] initWithString:@"A retained one"]; NSMutableString *thirdMutableOne = [NSMutableString stringWithString:simpleString];
If you are working with strings, you are probably going to need the length of your string objects from time to time to make specific decisions at runtime. Imagine this scenario: ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access