如何在基于块的API方法中使用非空和可空的Objective-C关键字 [英] How to use nonnull and nullable Objective-C keywords in block-based API method
问题描述
考虑以下方法
- (void)methodWithArg:(NSString *)arg1 andArg:(NSString *)arg2 completionHandler:(void (^)(NSArray *results, NSError *error))completionHandler;
使用新的nonnull
和nullable
注释关键字,我们可以按以下方式进行充实:
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:
指针缺少可为空类型说明符(__nonnull或 __nullable
Pointer is missing a nullability type specifier (__nonnull or __nullable)
它引用第三个参数(块1).
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
您可以立即使用非下划线形式的nullable和nonnull 在圆括号之后,只要类型是简单对象或 块指针.
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.
我尝试将这两个关键字之一放在任意位置(没有任何运气).还尝试了下划线前缀的变体(__nonnull
和__nullable
).
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?
推荐答案
这似乎可行
- (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...
有关更多信息,请参见 Swift博客
For more information, see Swift Blog
这篇关于如何在基于块的API方法中使用非空和可空的Objective-C关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!