為了更加規范代碼,讓開發者明確傳值要求,我們今天來介紹一下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<NSURL *> *failedURLs;
@property (strong, nonatomic, nonnull) NSMutableArray<SDWebImageCombinedOperation *> *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<NSURL *> *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.關鍵字不能用于基本數據類型,只能用于對象。