首先,如果我的英语不完全正确,抱歉。这不是我的母语,但我会尽力解释自己。
我很难理解以下问题。考虑以下代码:
// 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/