Search code examples
objective-cdereference

How dereference works in Objective-C


I was trying to understand dereferencing in Objective-C and wrote below two methods.

-(void)alterStringModelOne:(NSMutableString**)string{
    NSMutableString *str = [NSMutableString stringWithString:@"New string by string = &str"];

    string = &str; //Didn't work
}
-(void)alterStringModelTwo:(NSMutableString**)string{
    NSMutableString *str = [NSMutableString stringWithString:@"New string by *string = str"];

    *string = str; //It works
}

In above, ModelOne didn't work while ModelTwo does. How are these two statements different?

Edit: Tracing their address and type

myStr = b260 of type * CFString

---> Enters method model one

string = d9c4 of type ** NSMutableString //Parameter

str = f750 of * CFString //after str creation

string = d97c of type ** NSMutableString //After assignment: string = &str;

--> method returns

myStr = b260 * CFString

--> Enters method model two

string = d9c4 of type ** NSMutableString //Parameter

str = 0bc0 of * CFString //after str creation

string = 0bc0 of type * CFString //After assignment: *string = str;

--> Leaves method

myStr = 0bc0 of type * CFString


Solution

  • First of all: This is not specific to Objective-C. The same behavior exists in C and C++.

    string = &str;
    

    This modifies the value of the local variable string.

    *string = str;
    

    This modifies the value pointed to by string.

    Since string is a local variable, changing it (as seen in the first example) does not have any lasting effect. The value it points to is not local, though, so changing that (second example) does do what you want.