I recently came across an article on value passing and reference passing in Objective-C. Take notes
First look at the code:
- (void)viewDidLoad { [super viewDidLoad]; NSString *str = @"HelloWorld"; NSLog (@ "STR = % @, before invoking object address = % p, pointer address = % p \ n", STR, STR, & STR); [self changeMyStr:str]; NSLog (@ "STR = % @, after the call object address = % p, pointer address = % p \ n", STR, STR, & STR); }; - (void)changeMyStr:(NSString *) STR {NSLog(@" STR =%@, object address =%p, pointer address =%p \n", STR, STR,& STR); str = @"Nihao"; NSLog (@ "after method performs STR = % @, object address = % p, pointer address = % p \ n", STR, STR, & STR); }Copy the code
Execution Result:
Before calling STR =HelloWorld, object address =0x106705130, pointer address =0x310967878 before method execution STR =HelloWorld, object address =0x106705130, pointer address = 0x3109677B0 after method execution STR =Nihao, object address = 0x1067051B0, pointer address =0x3109677b0 After the call STR =HelloWorld, object address =0x106705130, pointer address =0x310967878Copy the code
As you can see, the value of STR does not change. (1) Before the call and before the assignment method is executed, the address of the object pointed to by STR is consistent, indicating that it points to the same object. However, the addresses of the Pointers are inconsistent, indicating that the STR pointer and the STR pointer before the call are not the same, that is, they are two Pointers, but they both point to the same object. ② Before and after the assignment method, the address of the object pointed to by STR is inconsistent, indicating that STR refers to a new object (@”Nihao”).
NSString * STR is a pointer, not a variable. Pointers are also value-passed, so the pointer variable of a parameter is not the same as the external pointer variable (as the “pointer address” of the code execution result verifies), but they all point to the same place before assigning a value to the pointer inside the function.
If there is fallacy, welcome to correct, common progress