Sign In/My Account | View Cart  

advertisement

AddThis Social Bookmark Button

Article:
  Strings in Cocoa, Part 2
Subject:   NSStrings are mutable, just not by us?
Date:   2001-07-20 14:09:04
From:   tophu
I am confused. The information presented here seems to be in direct contradiction.


On the first page we do this:


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


Then, on the second page, Mike says 'we cannot use the @"..." construct to directly create mutable strings. Remember that this construct created strings that are compiled and are always present. Obviously we cannot change a pre-compiled string...'


So, NSStrings can be modified by Cocoa internally, but not modified directly by us?


Or, perhaps, in the above example path is a pointer that points to address A in memory when it is created, and then when the +stringByAppendingPathExtension: method changes path, it is in fact changing the address that path pointer points to in memory to reference a different object. However, when we change an NSMutableString we are not changing the address value in the pointer, just the value of the object at that address.


Can someone clarify this for me?

Full Threads Oldest First

Showing messages 1 through 1 of 1.

  • Michael Beam photo NSStrings are mutable, just not by us?
    2001-07-20 21:41:05  Michael Beam | O'Reilly Author [View]

    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