Consider the following method
- (void)methodWithArg:(NSString *)arg1 andArg:(NSString *)arg2 completionHandler:(void (^)(NSArray *results, NSError *error))completionHandler;
With the new nonnull
and nullable
annotation keywords we can enrich it as follows:
- (void)methodWithArg:(nonnull NSString *)arg1 andArg:(nullable NSString *)arg2 completionHandler:(void (^)(NSArray *results, NSError *error))completionHandler;
but we also get this warning:
Pointer is missing a nullability type specifier (__nonnull or __nullable)
It refers to the third parameter (the block one).
The documentation doesn't cover with examples how to specify the nullability of block parameters. It states verbatim
You can use the non-underscored forms nullable and nonnull immediately after an open parenthesis, as long as the type is a simple object or block pointer.
I tried putting one of the two keywords for the block (in any position) without any luck. Also tried the underscore prefixed variants (__nonnull
and __nullable
).
Therefore my question is: how can I specify the nullability semantic for block parameters?
To define completions in a header file I did this
Of course, I agree with the accepted answer.
From apple developer blog: The Core: _Nullable and _Nonnull
This seems to be working
You need to specify nullability both for the block and its parameters...
EDIT: For more information, see Swift Blog
Here is what I have used for the NSError ** case:
You can also do like this:
It only depends which syntax you like more.
According to Apple Blog ("Nullability and Objective-C"), you can use
NS_ASSUME_NONNULL_BEGIN
andNS_ASSUME_NONNULL_END
.Within these regions, any simple pointer type will be assumed to be
nonnull
. Then you can just addnullable
for nullable object, which likeNSError **
type, should beNSError * _Nullable * _Nullable
id *
type, better useid _Nullable * _Nonnull
, it depends (may be you want a_Nullable id * _Nullable
type).NSObject *
type, you need put annotation after pointer, like thisNSObject * _Nullable * _Nonnull
Note
_Nonnull
and_Nullable
should used after pointer orid
(Apple does in the example codeAAPLListItem * _Nullable
), but the non-underscored formsnonnull
andnullable
can used after an open parenthesis.check more in "Nullability and Objective-C"
The
_Nullable id * _Nonnull
can be confused,id _Nullable * _Nonnull
is better understanding._Nonnull
and_Nullable
should used after pointer orid
(Apple does in the example codeAAPLListItem * _Nullable
)