ios - 为什么通过引用传递时指针值会改变?

标签 ios objective-c iphone

为什么下面的 NSLog 结果不同?

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

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

虽然以下 NSLog 结果相同?

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

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

最佳答案

好问题,但答案并不明显。

这一切都与与变量关联的所有权限定符有关。当您声明时:

NSView *view;

这是以下内容的简写:

NSView __strong * view;

即该引用由变量 view 强力保存。

但是当您声明时:

-(void)test:(UIView **)view

这是以下内容的简写:

-(void)test:(UIView * __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/

相关文章:

iOS - 使用相同的顺序从多个数组中获取唯一值

iphone - 未访问 cachedResponseForRequest 方法

iphone - 重新签署 IPA (iPhone)

ios - 动态链接无法打开应用程序,并且 "open in app"选项在上下文菜单中不可用

objective-c - 未正确设置可变字典键

ios - 安装 OSX Yosemite 后 Xcode 4.6.1 崩溃

ios - 需要在 IOS 的 mapview 上添加一个固定的叠加层

iphone - 这意味着什么? "mi_cmd_stack_list_frames: Not enough frames in stack."

iphone - Objective-C++ 支持多少 C++

IOS memcpy 纹理到双数组