为什么下面的 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 ARC和 NSError 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/