无法理解NSError/NSObject指针传递行为 [英] Cannot understand NSError/NSObject pointer passing behavior
问题描述
即使我已阅读 NSError * vs NSError ** 等.
我已经做了一些思考,但仍然有一些疑问.
I've done some thinking and still got some questions.
这是我写的:
NSError *error = [NSError errorWithDomain:@"before" code:0 userInfo:nil];
NSLog(@"outside error address: %p", &error];
[self doSomethingWithObj:nil error:&error];
为了测试上述NSError
方法,我这样写:
In order to test the above NSError
method, I wrote this:
- (id)doSomethingWithObj:(NSObject *)obj error:(NSError *__autoreleasing *)error
{
NSLog(@"inside error address: %p", error);
id object = obj;
if (object != nil)
{
return object;
}
else
{
NSError *tmp = [NSError errorWithDomain:@"after" code:0 userInfo:nil];
*error = tmp;
return nil;
}
}
但是我发现两个日志记录地址不同.为什么会这样?
But I found that the two logging addresses are different. Why is that?
2016-08-19 19:00:16.582 Test[4548:339654] outside error address: 0x7fff5b3e6a58
2016-08-19 19:00:16.583 Test[4548:339654] inside error address: 0x7fff5b3e6a50
它们不应该是相同的,因为那只是一个简单的值副本?如果它们应该不同,那么指针指针如何最终指向同一NSError
实例?
Shouldn't they be the same since that was just a simple value copy? If they should be different, how can pointer to pointer end up pointing to the same NSError
instance?
推荐答案
调用方中的变量的类型为NSError*
.该地址的类型为NSError* *
.函数期望NSError* __autoreleasing *
.因此,编译器将创建类型为NSError* __autoreleasing
的隐藏变量,将NSError*
复制到调用之前的隐藏变量中,并在调用之后将其复制回以获得__autoreleasing的语义.
The variable in the caller has type NSError*
. The address has type NSError* *
. The function expect NSError* __autoreleasing *
. Therefore the compiler creates a hidden variable of type NSError* __autoreleasing
, copies the NSError*
into the hidden variable before the call, and copies it back after the call to get the semantics of __autoreleasing right.
这篇关于无法理解NSError/NSObject指针传递行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!