问题描述
我正在尝试完成这个难题。
I'm trying to complete the puzzle.
__ 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.
__弱
类似于 __ 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:
所有这一切都在。
在NSError示例中,声明意味着 __strong
,隐含地:
In your NSError example, the declaration means __strong
, implicitly:
NSError * e = nil;
将转换为:
NSError * __strong error = nil;
当您拨打保存
方法时:
- ( 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 $ c来避免这种情况$ c>,直接。
You may avoid this by declaring the error object as __autoreleasing
, directly.
这篇关于在哪些情况下我们需要在ARC下编写__autoreleasing所有权限定符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!