advertisement

Article:
  Strings in Cocoa, Part 2
Subject:   NSStrings are mutable, just not by us?
Date:   2001-07-20 21:41:05
From:   mikebeam
Response to: NSStrings are mutable, just not by us?

You mentioned this bit of code:


NSString *path = @"Users/mike/textFile";
path = [path stringByAppendingPathExtension:@"txt"];


but in this code there is no changing of string objects. What we have is a string object pointed to by path in the first line. In the second line we are not changing that string object we created in the first line in any way. Rather, we are creating a new string object by taking the original and adding another string to the end of it. We're not changing the string, we're creating a new one, and then reassigning the variable path so that it points to the new string object returned by the method in the second line.


So in the last paragraph of your post, you've hit the right explanation of what is going on. And you were right about what happens when we change an NSMutableString.


Perhaps i could have made this example clearer by choosing a new variable name for the new object. Actually, we'll see in the next column how this is an example of letting objects loose, which needlessly takes up memory since there's no way we can send messages to the first string object in the code. This is because our way of accessing that object was through the "path" variable, but after the second line, that variable points to an object other than the first.


Hope that helps!


Mike