为了更加规范代码,让开发者明确传值要求,我们今天来介绍一下iOS9新增的几个字段,并结合SDWebImage第三方代码示例来分析:
1、nonnull的字面意思是不能为空,可以用来修饰属性方法的参数或者返回值,如果开发者传参nil,那么会有警告提示。如下:
//设置属性不能为空
@interface SDWebImageManager ()
@property (strong, nonatomic, readwrite, nonnull) SDImageCache *imageCache;
@property (strong, nonatomic, readwrite, nonnull) SDWebImageDownloader *imageDownloader;
@property (strong, nonatomic, nonnull) NSMutableSet *failedURLs;
@property (strong, nonatomic, nonnull) NSMutableArray *runningOperations;
@end
//设置方法中的参数不能为空,返回值不能为nil
/**
* Async check if image has already been cached on disk only
*
* @param url image url
* @param completionBlock the block to be executed when the check is finished
*
* @note the completion block is always executed on the main queue
*/
- (void)diskImageExistsForURL:(nullable NSURL *)url
completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock;
/**
*Return the cache key for a given URL
*/
- (nullable NSString *)cacheKeyForURL:(nullable NSURL *)url;
2、nullable:表示可以为空,这里表明对应的值可以为nil,且不会出现警告提示。
#import "SDWebImagePrefetcher.h"
@interface SDWebImagePrefetcher ()
@property (strong, nonatomic, nonnull) SDWebImageManager *manager;
@property (strong, atomic, nullable) NSArray *prefetchURLs; // may be accessed from different queue
@property (copy, nonatomic, nullable) SDWebImagePrefetcherCompletionBlock completionBlock;
@property (copy, nonatomic, nullable) SDWebImagePrefetcherProgressBlock progressBlock;
@end
3、null_resettable: get不能返回空, set可以为空。如果使用了null_resettable,必须要重写get方法处理传递的值为nil的情况,否则程序会崩溃。
//设置参数null_resettable
@property (nonatomic, copy, null_resettable) NSString *sex;
//不在get、set判断nil的情况,直接传参nil
[Nullable new].sex = nil;
//收到Xcode的提示
Synthesized setter 'setSex:' for null_resettable property 'sex' does not handle nil
下面我们设置get或set的nil设置
//.h文件中
//null_resettable 作用: get:不能返回为空, set可以为空,get方法必须重写
@property (nonatomic, copy, null_resettable) NSString *sex;
@property (nonatomic, copy, null_resettable) NSString *name;
//.m文件中重写get方法
- (NSString *)sex{
if (_sex == nil) {
_sex = @"sex问世间情为何物";
}
return _sex;
}
- (NSString *)name
{
if (_name == nil) {
_name = @"name直教生死相许";
}
return _name;
}
//调用方法,输出效果:
Nullable *nul = [[Nullable alloc]init];
nul.name = nil;
nul.sex = nil;
NSLog(@"设置了nil,返回值sex:%@---name:%@",nul.sex,nul.name);
//打印数据如下:
设置了nil,返回值sex:sex问世间情为何物---name:name直教生死相许
4、_Null_unspecified:不确定是否为空,两种写法:
//这个方法基本上用不到,了解就可以了
@property (nonatomic, strong) NSString *__null_unspecified name;
@property (nonatomic, strong) NSString *_Null_unspecified name;
下面补充个注意点:
1.关键字仅仅是提供警告,并不会报编译错误。当属性关键字为nonnull的时候,即使属性置为nil,也只是报警告而已,不会报错。
2.关键字不能用于基本数据类型,只能用于对象。