我有一个自定义的UITableViewController类,它在我的应用程序的一些ViewControllers之间共享。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
...
// Check if we are almost at the end of the scroll. If so, start fetching.
// Doing this here is better than overriding scrollViewDidEndDragging
if (indexPath.row >= [self.tableView numberOfRowsInSection:0] - 3) {
[self refill];
}
return cell;
}
我想在用户点击页面底部之前先进行抢占式提取。
然而,我注意到如果用户向上滚动然后再向下滚动,我的VC将触发另一次提取。
所以我想出了一个标志isFetching,它检查以防止双重抓取。不幸的是我正在运行异步代码,我需要一种方法来在我的提取操作完成后重置这个标志。
FeedVC:
- (void)refill {
if (self.continueFetching && !self.isFetching) {
NSLog(@"Fetching started");
self.isFetching = true;
AFJSONRequestOperation *operation = [self.delegate refill:^{
NSLog(@"Fetching completed");
self.isFetching = false;
}];
[self.pendingOperations addObject:operation];
}
}
代表:
- (AFJSONRequestOperation *)refill:(void (^)(void))finishCallback {
return [[ItemStore sharedInstance] fetchItemsForFeed:^(int itemsFetched, int nextOffset, bool hasNextPage) {
finishCallback();
} withFailureBlock:^{
finishCallback();
}];
}
我发现为了翻转布尔值而传递一个完成集团是非常痛苦的。有人有更好的推荐吗?
答案 0 :(得分:0)
精化:
typedef void(^block_t)(void);
typedef void(^success_block_t)(int itemsFetched, int nextOffset, bool hasNextPage);
FeedCV:
/****************************************************************************/
/*!
@note assume the declarations:
@property (nonatomic,strong) NSOperation* fetchOp;
@property (nonatomic,strong) NSOperationQueue* operationQueue;
*/
/****************************************************************************/
- (void) refill
{
if (self.fetchOp) { //fetch is in progress
return;
}
__block __weak id weakSelf = self;
block_t completionBlock = ^{ //this will happen on a BG thread
//Implement what ever logic seems to fit your FeedVC uppon completion
//This will be called on the operation thread, so don't update UI here
//Move to main thread UI updates
[weakSelf setFetchOp:nil];
};
self.fetchOp = [self.delegate refill:completionBlock];
// successBlock:nil
// failBlock:nil];
//If you can't change your delegate code then:
//self.fetchOp = [self.delegate refill:nil];
//[self.fetchOp setCompletionBlock:completionBlock];
[self.operationQueue addOperation:self.fetchOp];
}
/****************************************************************************/
代表:
/****************************************************************************/
/*!
@note If you can change this API add support for the blocks
*/
/****************************************************************************/
- (AFJSONRequestOperation*) refill:(block_t)completionBlock
// successBlock:(success_block_t)success
// failBlock:(block_t)fail
{
AFJSONRequestOperation* op = [[ItemStore sharedInstance] fetchItemsForFeed:nil/*success*/
withFailureBlock:nil/*fail*/];
[op setCompletionBlock:completionBlock];
return op;
}
/****************************************************************************/