Changes

Jump to: navigation, search

Working with String Objects in Objective-C

2,060 bytes added, 14:50, 3 November 2009
no edit summary
Length of string = 5
</pre>
 
Constant string objects are actually instantiated from the NSConstantString class which, much like the other classes we will look at in this chapter, is actually a subclass of the NSString class. In practice, given the way that constant strings are used, it is unlikely that you will need to specifically declare your string constants as being of type NSConstantString. It is more likely that you will declare the string as we have done in this section and let the compiler handle the rest.
== Creating Mutable and Immutable String Objects ==
 
Two additional types of Objective-C string objects are ''mutable'' and ''immutable''. When you create a string object of type ''NSString'' you are creating an ''immutable'' string object. This means that once a string has been assigned to the object, that string cannot subsequently be modified in any way.
 
<pre>
NSString *string1 = @"This string is immutable";
</pre>
 
Mutable string objects, on the other hand, are declared using the ''NSMutableString'' class and allow the string contained within the object to be modified using a variety of methods (some of which will be covered in the remainder of this chapter).
 
<pre>
NSMutableString *string2 = @"This string is mutable";
</pre>
 
Once a string has been declared as immutable, the only way to get a mutable version of the string is to create a mutable string object and copy the contents of the immutable string object to it. This can be achieved using the NSMutableString ''stringWithString'' class method. For example:
 
<pre>
NSString *string1 = @"This string is string";
NSMutableString *string2;
 
string2 = [NSMutableString stringWithString: string1];
</pre>
 
Once executed, the above code will create an immutable string object (string1) initialized with the text "This is a string" and an empty immutable string (string2). The ''stringWithString'' class method the NSMutableString class is then called, passing though the immutable string1 as an argument. This methods returns a new object containing the immutable string and assigns it to string2. We now have a mutable copy of the string object.
 
== Getting the Length of a String ==

Navigation menu