【问题标题】:Repointing a pointer inside an Objective-C method在 Objective-C 方法中重新指向指针
【发布时间】:2013-02-04 17:15:51
【问题描述】:

首先,对不起,如果我的英语不是绝对正确的。这不是我的母语,但我会尽力解释自己。

我很难理解以下问题。考虑以下代码:

// On a class named SPOTest
- (void)referenceTest:(NSMutableString *)originalText
{
    [originalText appendString:@" world!!!"]
}

// From another place
NSMutableString *myText = [NSMutableString stringWithString:@"Hello"];
NSLog(@"Contents of myText BEFORE: %@", myText);
SPOTest *myTest = [[SPOTest alloc] init];
[myTest referenceTest:myText];
NSLog(@"Contents of myText AFTER: %@", myText);

输出:

Contents of myText BEFORE: Hello
Contents of myText AFTER: Hello world!!!

我觉得可以理解。我正在使用指针,所以如果我改变事物和指针的结尾,我会为所有指向它的指针改变那个事物。另一方面,如果我更改代码并执行此操作:

// On a class named SPOTest
- (void)referenceTest:(NSMutableString *)originalText
{
    NSMutableString *newText = [NSMutableString stringWithString:@"Hello world!!!"];
    originalText = newText;
}

// From another place
NSMutableString *myText = [NSMutableString stringWithString:@"Hello"];
NSLog(@"Contents of myText BEFORE: %@", myText);
SPOTest *myTest = [[SPOTest alloc] init];
[myTest referenceTest:myText];
NSLog(@"Contents of myText AFTER: %@", myText);

然后我明白了:

Contents of myText BEFORE: Hello
Contents of myText AFTER: Hello

这是为什么呢?我想正确的方法是使用双重间接和类似于NSError 机制的实现,但我想了解为什么我会获得这种行为。如果我可以从第一个示例中的referenceTest: 方法更改myText 指针的内容和结尾,为什么我不能从第二个示例中的相同方法更改myText 的地址?

我知道我遗漏了一些微不足道的东西,但我找不到它,我想了解这一点,以便更好地理解 NSError 机制背后的原因。

谢谢!

【问题讨论】:

    标签: objective-c pointers


    【解决方案1】:

    在第二种情况下,您正在更改该指针的本地副本。如果要在调用范围内重新指向它,则需要使用指向指针的指针,即:

    - (void)referenceTest:(NSMutableString **)originalText
    {
        NSMutableString *newText = [NSMutableString stringWithString:@"Hello world!!!"];
        *originalText = newText;
    }
    

    这样称呼它:

    [myTest referenceTest:&myText];
    

    值得注意的是 stringWithString 返回一个自动释放的字符串,这意味着你的函数也是。

    【讨论】:

    • 或者更好的是,return 新字符串。
    【解决方案2】:

    对象和指向对象的指针是有区别的。

    有人创建了一个 NSMutableString 对象,它存在于内存中的某处。我们真的不在乎它在哪里。有人收到了指向 NSMutableString 对象的 NSMutableString*。该 NSMutableString* 的副本已提供给您的方法 referenceTest。可以有任意数量的指向该 NSMutableString 对象的指针,但只有一个对象。

    appendString 方法改变了 NSMutableString 对象本身。

    stringWithString 方法创建一个新的 NSMutableString 对象并返回一个指向它的指针。所以现在我们有两个对象,newText 是指向第二个对象的指针。当您将 newText 分配给 originalText 时, originalText 将成为指向第二个 NSMutableString 对象的指针。但是, originalText 只是您方法中的参数。调用方法持有的指针不会因此而改变。

    【讨论】:

      猜你喜欢
      • 2010-11-08
      • 2011-05-19
      • 1970-01-01
      • 2014-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多