Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Objective-C方法中重新初始化指针_Objective C_Pointers - Fatal编程技术网

在Objective-C方法中重新初始化指针

在Objective-C方法中重新初始化指针,objective-c,pointers,Objective C,Pointers,首先,如果我的英语不是绝对正确的话,对不起。这不是我的母语,但我会尽力解释我自己 我很难理解以下问题。考虑以下代码: // On a class named SPOTest - (void)referenceTest:(NSMutableString *)originalText { [originalText appendString:@" world!!!"] } // From another place NSMutableString *myText = [NSMutableS

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

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

// 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返回一个自动释放的字符串,这意味着您的函数也是自动释放的。

对象和指向对象的指针之间有区别

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

appendString方法更改NSMutableString对象本身


stringWithString方法创建一个新的NSMutableString对象并返回指向该对象的指针。现在我们有两个对象,newText是指向第二个对象的指针。将新文本指定给originalText时,originalText将成为指向第二个NSMutableString对象的指针。但是,originalText只是方法中的参数。调用方法持有的指针不会因此而更改

或者更好的是,
返回新字符串。