Object-C中的Nullability语法

2020-03-13  本文已影响0人  不能遮掩的激昂

nullable 、_Nullable、__nullable 被修饰者可空
nonnull 、_Nonnull 、__nonnull 被修饰者不能为空

示列:

- (nullable NSString *)function;
- (NSString * _Nullable) function;
- (NSString * __nullable) function;
@property (nonatomic, copy, nullable) NSString * param;
@property (nonatomic, copy) NSString * __nullable param;
@property (nonatomic, copy) NSString * _Nullable param;
- (void)functionWithParam:(nullable NSString *) param;
- (void)functionWithParam:(NSString * _Nullable) param;
- (void)functionWithParam:(NSString * __nullable) param;

而对于 双指针类型对象 、Block 的返回值、Block 的参数 、C函数的参数等,这时候就不能用 nonnull/nullable 修饰,只能用带下划线的 __nonnull/__nullable 或者 _Nonnull/_Nullable


- (void)methodWithError:(NSError * _Nullable * _Nullable)error
- (void)methodWithError:(NSError * __nullable * __nullable)error
- (void)methodWithBlock:(nullable void (^)())block; 
- (void)methodWithBlock:(void (^ _Nullable)())block;
- (void)methodWithBlock:(void (^ __nullable)())block;
- (void)methodWithBlock:(id __nonnull (^)())block;
- (void)methodWithBlock:(id _Nonnull (^)())block;
- (void)methodWithBlock:(void (^ _Nullable)())block;
- (void)methodWithBlock:(void (^ __nullable)())block;
- (void)methodWithBlock:(nullable id __nonnull (^)(id __nullable params))block;
- (void)methodWithBlock:(id __nonnull (^ __nullable)(id __nullable params))block;
- (void)methodWithBlock:(id _Nonnull (^ _Nullable)(id _Nullable params))block;

int UIApplicationMain(int argc,
                      char * _Nullable argv[_Nonnull],
                      NSString * _Nullable principalClassName,
                      NSString * _Nullable delegateClassName);

总结

使用规范:

《Nullability and Objective-C》

苹果为了减轻我们的工作量,专门提供了两个宏:NS_ASSUME_NONNULL_BEGINNS_ASSUME_NONNULL_END。在这两个宏之间的代码,所有简单指针对象都被假定为 nonnull,因此我们只需要去指定那些 nullable指针对象即可。如下代码所示:

NS_ASSUME_NONNULL_BEGIN
@interface TestClass ()
- (void)methodWithParam:(nullable id)Param;
@end
NS_ASSUME_NONNULL_END
上一篇下一篇

猜你喜欢

热点阅读