我正在努力向头文件的一部分添加一些可空性注释,并且我希望该 block 假设为非空,但之后几乎所有方法都发出警告说我需要添加可空性注释。
下面的示例代码:
NS_ASSUME_NONNULL_BEGIN
- (void)testMethodWithParameter:(NSString *)par otherParameter:(NSString *)otherPar;
NS_ASSUME_NONNULL_END
- (void)methodThatShouldntNeedAnnotationWithText:(NSString *)txt;
//Warning: Pointer is missing a nullability type specifier (_Nonnull, _Nullable, or _Null_unspecified)
我是否错误地理解了这些宏?我认为它会包含据说在 BEGIN/END block 中被审计的部分,但外面的所有内容仍然是 _Null_unspecified
这是按预期工作的,还是我必须做些什么才能使它按我的想法工作?
最佳答案
NS_ASSUME_NONNULL_BEGIN
使任何参数都被假定为非空变量,因此:
NS_ASSUME_NONNULL_BEGIN
- (void)testMethodWithParameter:(NSString *)par otherParameter:(NSString *)otherPar;
NS_ASSUME_NONNULL_END
转换为:
- (void)testMethodWithParameter:(nonnull NSString *)par otherParameter:(nonnull NSString *)otherPar;
因此,没有 NS_ASSUME_NONNULL_BEGIN
并不意味着每个参数都被假定为 nullable
或 unspecified
,您仍然必须定义它。因此,对于另一种方法,您必须指定您想要的内容,如果您希望文本可以是 nullable
,则将关键字添加到参数中,如下所示:
- (void)methodThatShouldntNeedAnnotationWithText:(nullable NSString *)txt;
关于ios - NS_ASSUME_NONNULL_END 之后的可空性注释警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39398381/