How to use nonnull and nullable Objective-C keywords in block-based API method

albertodebortoli picture albertodebortoli · Apr 15, 2015 · Viewed 66.3k times · Source

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?

Answer

Fabio Ritrovato picture Fabio Ritrovato · Apr 15, 2015

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