How to use nonnull and nullable Objective-C keywords in block-based API method
According to Apple Blog ("Nullability and Objective-C"), you can use
NS_ASSUME_NONNULL_BEGIN
and NS_ASSUME_NONNULL_END
.
Within these regions, any simple pointer type will be assumed to be nonnull
. Then you can just add nullable
for nullable object, which like
NS_ASSUME_NONNULL_BEGIN
@interface MyClass: NSObject
- (void)methodWithArg:(NSString *)arg1 andArg:(nullable NSString *)arg2 completionHandler:(void (^)(NSArray *results, NSError *error))completionHandler;
@end
NS_ASSUME_NONNULL_END
- if error is
NSError **
type, should beNSError * _Nullable * _Nullable
- if object is
id *
type, better useid _Nullable * _Nonnull
, it depends (may be you want a_Nullable id * _Nullable
type). - if object is
NSObject *
type, you need put annotation after pointer, like thisNSObject * _Nullable * _Nonnull
Note
_Nonnull
and _Nullable
should used after pointer or id
(Apple does in the example code AAPLListItem * _Nullable
), but the non-underscored forms nonnull
and nullable
can used after an open parenthesis.
However, in the common case there’s a much nicer way to write these annotations: within method declarations you can use the non-underscored forms
nullable
andnonnull
immediately after an open parenthesis, as long as the type is a simple object or block pointer.
check more in "Nullability and Objective-C"
For safety, there are a few exceptions to this rule:
typedef
types don’t usually have an inherent nullability—they can easily be either nullable or non-nullable depending on the context. Therefore,typedef
types are not assumed to benonnull
, even within audited regions.- More complex pointer types like
id *
must be explicitly annotated. For example, to specify a non-nullable pointer to a nullable object reference, use_Nullable id * _Nonnull
.- The particular type
NSError **
is so often used to return errors via method parameters that it is always assumed to be a nullable pointer to a nullableNSError
reference.
The _Nullable id * _Nonnull
can be confused, id _Nullable * _Nonnull
is better understanding.
_Nonnull
and _Nullable
should used after pointer or id
(Apple does in the example code AAPLListItem * _Nullable
)
This seems to be working
- (void)methodWithArg:(nonnull NSString *)arg1
andArg:(nullable NSString *)arg2 completionHandler:(nullable void (^)
(NSArray * _Nullable results, NSError * _Nonnull error))completionHandler
You need to specify nullability both for the block and its parameters...
EDIT: For more information, see Swift Blog
You can also do like this:
- (id __nullable)methodWithArg:(NSString * __nullable)arg1
andArg:(NSString * __nonnull)arg2
completionHandler:(void (^ __nonnull)(NSArray * __nonnull results, NSError * __nullable error))completionHandler;
It only depends which syntax you like more.