关于Objective-C中_Nullable在NSError双指针参数间位置的疑问
_Nullable Goes Between the Two Asterisks in Objective-C's Error Parameter Great question! Let's break this down step by step because Objective-C's nullable annotations can feel a bit tricky when dealing with pointers to pointers.
First, let's recap the pointer hierarchy here:
NSError **erroris a pointer to a pointer (a "double pointer"). The outer pointer points to an inner pointer, which in turn points to anNSErrorobject.- The purpose of this parameter is to let the method write an error object (or
nil) into the inner pointer you pass in.
The Rule for Nullability Annotations
Objective-C's _Nullable and _Nonnull modifiers directly modify the pointer type they are adjacent to. So you have to place the modifier exactly where it describes the nullable nature of the specific pointer you care about.
Why Between the Asterisks?
When Apple updated this API with nullability annotations, they needed to communicate:
The inner pointer (the
NSError *that the outer pointer points to) can benil(meaning no error occurred).
Placing _Nullable between the two asterisks (NSError * _Nullable *error) does exactly that:
- The
_Nullableis adjacent to the middle*, so it modifies theNSError *type (the inner pointer). This tells callers: "The error object pointer we write back to you might be nil."
What Happens If We Put It Elsewhere?
Let's look at the wrong placements to clarify:
_Nullable NSError **error: This would mean the outer double pointer itself can benil. But the API requires you to pass a valid pointer to a pointer (so the method has somewhere to write the error if it occurs), so this is not what we want.NSError ** _Nullable error: This also modifies the outer double pointer, saying it can be nil—again, not matching the API's intended behavior.
To Sum It Up
The placement of _Nullable directly maps to which pointer level we're annotating. Since the API's contract is about the inner error pointer being nullable (not the outer pointer to that pointer), we put the modifier right between the two asterisks.
内容的提问来源于stack exchange,提问作者Drew

