How the job is played in object C

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

-(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 the above example, ModelOne does not work while ModelTwo is running. How do these two statements differ? Can someone help me understand? Thanks.

Edit: tracking their address and type

myStr = b260 type * CFString

---> Included in the one method model

string = d9c4 type ** NSMutableString // Parameter

str = f750 of * CFString // after creating str

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

-> returns

myStr = b260 * CFString

-> Introduces a method model two

string = d9c4 type ** NSMutableString // Parameter

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

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

-> Leaf Method

myStr = 0bc0 type * CFString

+4
source share
2 answers

First of all: this does not apply to Objective-C. The same behavior exists in C and C ++.

 string = &str; 

This changes the value of the local variable string .

 *string = str; 

This changes the value pointed to by string .

Since string is a local variable, changing it (as seen from the first example) has no lasting effect. The value that this points to is not local, so changing this (second example) does what you want.

+4
source

It works the same way as in C. Objective-C, pointers are accessed by objects, so in:

 NSMutableString *string; 

string declared as a pointer to the structure of the object, and you normally work with it, as if it were an object directly. Then you passed the address of this pointer, which we consider as the object itself. Sort of:

 (NSMutableString **)string 

actually

 ((object)*)string 

If you want to assign something to the original object, you should use the value that this string pointer points to, and not yourself (as happens in your model), otherwise you will end up changing what it points to and not what that represented his address. That's why your second model works. You put str , which is a pointer to an object (which we again consider to be just an object) above the original pointer, which is the so-called object that the string pointer points to.

Be careful when managing memory while doing this.

0
source

All Articles