YTKChainRequest
的 理解key
?源碼 注釋, 很清楚。
///? The success callback. Note if this value is not nil and `requestFinished` delegate method is
///? also implemented, both will be executed but delegate method is first called. This block
///? will be called on the main queue.
@property (nonatomic, copy, nullable) YTKRequestCompletionBlock successCompletionBlock;
///? The failure callback. Note if this value is not nil and `requestFailed` delegate method is
///? also implemented, both will be executed but delegate method is first called. This block
///? will be called on the main queue.
@property (nonatomic, copy, nullable) YTKRequestCompletionBlock failureCompletionBlock;
block 的 優(yōu)化
- (void)loginButtonPressed:(id)sender {
? ? RegisterApi *api = [[RegisterApi ?alloc ] ?init];? ? ? ?
?[api ?startWithCompletionBlockWithSuccess: ?^(YTKBaseRequest ?* ?request) {
//你可以直接在這里使用 self
NSLog(@"succeed");? ? ? ??
}
failure:^(YTKBaseRequest *request) {
//你可以直接在這里使用 self
NSLog(@"failed");? ? ??
? }];?
?? }}
注意:你可以直接在 block 回調(diào)中使用self,不用擔(dān)心循環(huán)引用。因?yàn)?YTKRequest 會(huì)在執(zhí)行完 block 回調(diào)之后,將相應(yīng)的 block 設(shè)置成 nil。從而打破循環(huán)引用。
源碼:?
@implementation YTKRequest
- (void)start {
if (self.ignoreCache) {
[self startWithoutCache];
return;}
// Do not cache download request.
if (self.resumableDownloadPath) {
[self startWithoutCache];
return;}
if (![self loadCacheWithError:nil]) {
[self startWithoutCache];
return;}
_dataFromCache = YES;
dispatch_async(dispatch_get_main_queue(), ^{
[self requestCompletePreprocessor];
[self requestCompleteFilter];
YTKRequest *strongSelf = self;
[strongSelf.delegate requestFinished:strongSelf];
if (strongSelf.successCompletionBlock) {
strongSelf.successCompletionBlock(strongSelf);}
[strongSelf clearCompletionBlock];? // nil out to break the retain cycle.
});
}
- (void)clearCompletionBlock {
// nil out to break the retain cycle.
self.successCompletionBlock = nil;
self.failureCompletionBlock = nil;
}