objective-c - 在 Objective-C 方法中重新指向指针

标签 objective-c pointers

首先,如果我的英语不完全正确,抱歉。这不是我的母语,但我会尽力解释自己。

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

// 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 机制背后的推理。

谢谢!

最佳答案

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

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

并这样调用它:

[myTest referenceTest:&myText];

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

关于objective-c - 在 Objective-C 方法中重新指向指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14691848/

相关文章:

c++ - 从动态数组中删除一个动态对象

ios - 调整导航栏标题字体大小以适应文本

objective-c - 限制 UIScrollView 一次只能滚动一页

iphone - 设置方法所需静态对象的正确方法

c - C 函数原型(prototype)返回二维数组

c++ - std::shared_ptr 的 use_count 有哪些递增方式?

c++ - 变量名和指针有什么区别?

objective-c - 什么时候应该在 Objective-C 中使用 nil 和 NULL?

objective-c - 将 NSNumber 转换为 NSDecimalNumber

c - * C 指针中的符号