1.8. Allocating and Making Use of Strings
Problem
You want to 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=[NSStringstringWithString:@"This is another simple string"];NSString*oneMorestring=[[NSStringalloc]initWithString:@"One more!"];NSMutableString*mutableOne=[NSMutableStringstringWithString:@"Mutable String"];NSMutableString*anotherMutableOne=[[NSMutableStringalloc]initWithString:@"A retained one"];NSMutableString*thirdMutableOne=[NSMutableStringstringWithString: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