You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Objective-C初学者疑问:局部变量赋值实例变量基础问题

Hey there! Let's break down your code and clear up that assignment confusion you're having with Objective-C.

What's Happening in Your 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 xyz with stringWithUTF8String:, it holds the address of the user-input string object.
  • _str = xyz copies the address stored in xyz into _str. Now both _str and xyz point 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 what xyz points to—now it points to the constant string @"omg" instead. Since _str is 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:42:17