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 的 优化
- (void)loginButtonPressed:(id)sender {
RegisterApi *api = [[RegisterApi alloc ] init];
[api startWithCompletionBlockWithSuccess: ^(YTKBaseRequest * request) {
//你可以直接在这里使用 self
NSLog(@"succeed");
}
failure:^(YTKBaseRequest *request) {
//你可以直接在这里使用 self
NSLog(@"failed");
}];
}}
注意:你可以直接在 block 回调中使用self,不用担心循环引用。因为 YTKRequest 会在执行完 block 回调之后,将相应的 block 设置成 nil。从而打破循环引用。
源码:
@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;
}
网友评论