OGeek|极客世界-中国程序员成长平台

标题: ios - 为什么通过引用传递时指针值会改变? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 12:31
标题: ios - 为什么通过引用传递时指针值会改变?

为什么下面的 NSLog 结果不一样?

UIView *view = [UIView new];
NSLog(@"%p",&view); //0x7fff59c86848
[self test:&view];

-(void)testUIView **)view{
   NSLog(@"%p",view); // 0x7fff59c86840
}

虽然以下 NSLog 结果相同?

 NSInteger j = 1;
 NSLog(@"%p", &j);//0x7fff5edc7ff8
 [self test1:&j];

- (void)test1NSInteger *)j{
   NSLog(@"%p", j);//0x7fff5edc7ff8
}



Best Answer-推荐答案


好问题,答案不明显。

这完全与与变量相关的所有权限定符有关。当你声明:

NSView *view;

这是以下的简写:

NSView __strong * view;

即引用由变量 view 强烈持有。

但是当你声明时:

-(void)testUIView **)view

这是以下的简写:

-(void)testUIView * __autoreleasing *)view

这里 view 是指向变量的类型指针 __autoreleasing 指向 UIView 的指针。

__strong__autoreleasing 之间存在差异的原因在于 Apple 术语的 call-by-writeback 并在 Variable Qualifiers in Apple's "Transitioning to ARC Release Notes" 中进行了解释。在 Ownership qualification in CLANG Documentation: Automatic Reference Counting .还解释了 SO 问题 Handling Pointer-to-Pointer Ownership Issues in ARCNSError and __autoreleasing .

简而言之:指向 __strong 变量的指针不能作为指向 __autoreleasing 变量的指针传递。为了支持你这样做,编译器引入了一个隐藏的临时变量并传递它的地址。 IE。您的代码被有效地编译为:

UIView *view = [UIView new];
NSLog(@"%p",&view);
UIView __autoreleasing * compilerTemp = view;
[self test:&compilerTemp];
view = compilerTemp;

因此您看到的地址不同。

关于ios - 为什么通过引用传递时指针值会改变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41033513/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4