在哪些情况下我们需要在 ARC 下编写 __autoreleasing 所有权限定符? [英] In which situations do we need to write the __autoreleasing ownership qualifier under ARC?
问题描述
我正在尝试完成拼图.
__strong
是所有 Objective-C 可保留对象指针(如 NSObject、NSString 等)的默认值.这是一个强引用.ARC 使用范围末尾的 -release
来平衡它.
__strong
is the default for all Objective-C retainable object pointers like NSObject, NSString, etc.. It's a strong reference. ARC balances it with a -release
at the end of the scope.
__unsafe_unretained
等于旧方式.用于不保留可保留对象的弱指针.
__unsafe_unretained
equals the old way. It's used for a weak pointer without retaining the retainable object.
__weak
与 __unsafe_unretained
类似,不同之处在于它是一个自动归零的弱引用,这意味着一旦引用的对象被释放,指针就会被设置为 nil.这消除了悬空指针和 EXC_BAD_ACCESS 错误的危险.
__weak
is like __unsafe_unretained
except that it's an auto-zeroing weak reference meaning that the pointer will be set to nil as soon as the referenced object is deallocated. This eliminates the danger of dangling pointers and EXC_BAD_ACCESS errors.
但是 __autoreleasing
到底有什么用?我很难找到有关何时需要使用此限定符的实际示例.我相信它仅适用于需要指针指针的函数和方法,例如:
But what exactly is __autoreleasing
good for? I'm having a hard time finding practical examples on when I need to use this qualifier. I believe it's only for functions and methods which expect a pointer-pointer such as:
- (BOOL)save:(NSError**);
或
NSError *error = nil;
[database save:&error];
在 ARC 下必须以这种方式声明:
which under ARC has to be declared this way:
- (BOOL)save:(NSError* __autoreleasing *);
但这太含糊了,我想完全理解为什么.我发现的代码片段将 __autoreleasing 放在两颗星之间,这对我来说看起来很奇怪.类型是 NSError**
(指向 NSError 的指针),那么为什么将 __autoreleasing
放在星星之间而不是简单地放在 NSError**前面代码>?
But this is too vague and I'd like to fully understand why. The code snippets I find place the __autoreleasing inbetween the two stars, which looks weird to me. The type is NSError**
(a pointer-pointer to NSError), so why place __autoreleasing
inbetween the stars and not simply in front of NSError**
?
此外,可能还有其他情况我必须依赖 __autoreleasing
.
Also, there might be other situations in which I must rely on __autoreleasing
.
推荐答案
你说得对.正如官方文档所解释的:
You're right. As the official documentation explains:
__autoreleasing 表示通过引用 (id *) 传递并在返回时自动释放的参数.
__autoreleasing to denote arguments that are passed by reference (id *) and are autoreleased on return.
所有这些都在 ARC 过渡指南.
在您的 NSError 示例中,声明意味着 __strong
,隐式:
In your NSError example, the declaration means __strong
, implicitly:
NSError * e = nil;
将转换为:
NSError * __strong error = nil;
当您调用 save
方法时:
- ( BOOL )save: ( NSError * __autoreleasing * );
然后编译器必须创建一个临时变量,设置在 __autoreleasing
.所以:
The compiler will then have to create a temporary variable, set at __autoreleasing
. So:
NSError * error = nil;
[ database save: &error ];
将转换为:
NSError * __strong error = nil;
NSError * __autoreleasing tmpError = error;
[ database save: &tmpError ];
error = tmpError;
您可以通过直接将错误对象声明为 __autoreleasing
来避免这种情况.
You may avoid this by declaring the error object as __autoreleasing
, directly.
这篇关于在哪些情况下我们需要在 ARC 下编写 __autoreleasing 所有权限定符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!