Objective-C初学者疑问:局部变量赋值实例变量基础问题
Hey there! Let's break down your code and clear up that assignment confusion you're having with Objective-C.
init Method? First, let's look at the key lines in your initialization code that are causing the confusion:
-(id) init{ self=[super init]; char c[50]; scanf("%s",c); NSString *xyz=[NSString stringWithUTF8String:c]; NSLog(@"%p",xyz); // Prints address of the user-input string object _str=xyz; // _str now points to the same object as xyz xyz=@"omg"; // xyz is re-assigned to point to the @"omg" constant string NSLog(@"%p",_str); // Still prints the original user-input string's address return self; }
The Core Concept: Pointers in Objective-C
In Objective-C, variables like NSString *xyz are pointers—they don't store the actual string data, they store the memory address of where the string object lives. Here's what's happening step by step:
- When you create
xyzwithstringWithUTF8String:, it holds the address of the user-input string object. _str = xyzcopies the address stored inxyzinto_str. Now both_strandxyzpoint to the same exact object in memory.- When you do
xyz = @"omg", you're not modifying the original user-input string. You're just changing whatxyzpoints to—now it points to the constant string@"omg"instead. Since_stris a separate pointer variable, its stored address doesn't change.
Think of it like this: Imagine you have two notes (pointers) both written with the same street address (object memory location). If you erase one note and write a new address on it, the other note still has the original address written down. That's exactly what's happening here with _str and xyz.
If You Wanted _str to Update (Just for Context)
If you actually wanted changing xyz to affect _str, you'd need to use a pointer-to-pointer, but that's not necessary for your current use case. For your code as written, the behavior is completely expected—_str keeps pointing to the original user-input string because you only changed where xyz points, not the object itself.
内容的提问来源于stack exchange,提问作者Vinod Pn

