Objective-C/Xcode question on pointers and variables

Discussion in 'Mac Programming' started by Sandy Santra, Apr 15, 2009.

  1. Sandy Santra macrumors 6502

    Feb 1, 2008
    My study guide says:

    It is possible to declare and initialize the pointer variable for a string in one go:

    NSString *favoriteActress = @"Julia";
    No problem. I (sort of) understand that.

    Then it says: "Once you have initialized the variable, i.e. favoriteComputer, you may give the variable another value, but you cannot change the string itself" and gives the following code:

    #import <foundation/foundation.h>
    int main (int argc, const char *argv[])
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    NSString *favoriteComputer;
    favoriteComputer = @"iBook";
    favoriteComputer = @"MacBook Pro";
    NSLog(@"%@", favoriteComputer);
    [pool release];
    return 0;
    This is sort of confusing for two reasons:

    (1) Is the second line "favoriteComputer = @"MacBook Pro";" the "giving the variable another value" that the book mentions? I get the impression that when you give it another variable like that, it wipes away the first variable given, right?

    (2) What does the book mean by "you cannot change the string itself"? Very confused on this one. favoriteComputer is a variable of type "pointer" that points to an address. iBook and MacBook Pro are values that it took (except that doesn't make sense, unless those two things are themselves variables defined somewhere else). What am I missing here?

    Any explanation(s) greatly appreciated! Thanks..
  2. scottb99 macrumors newbie

    Apr 14, 2009
    First, in C, this would be:
    char *mychars = "test string";

    and the variable is just a pointer, and it points to a string constant.
    In that case it may be bad to change/can not change.

    In your case though, you may want to look at NSMutableString.

    Scott Becker
  3. lee1210 macrumors 68040


    Jan 10, 2005
    Dallas, TX
    A variable holds a value. In the case of primitives like int, this value stores a number. In the case of a pointer (indicated with a *), the value that is stored is a memory address where some data is stored. In Objective-C, all objects are referenced in this manner, so you always have a pointer to the object.

    In this case, the value stored in favoriteComputer is a pointer to an NSString object. The value of the pointer is changed from the original memory where the NSString literal @"iBook" is stored to point instead to the memory where the NSString literal @"Macbook Pro" is stored. The only memory associated with favoriteComputer is the space needed to store a memory address. This is being changed.

    Regarding not being able to change the string itself, that just means you can't change the value in the memory pointed to. Since NSString is unmutable, this isn't really an option anyway.


Share This Page