我有一个包含两个部分的 UITableView,其中每个部分都需要调用 REST API 来获取数据。我正在使用 MKNetworkKit 进行通话。我的问题是我应该如何为 UITableView 填充 NSMutableArray 以确保数据始终正确,即使在“拉动刷新”之后也是如此。我只是觉得我对这一切都错了。
这是我现在的代码:
MKNetworkEngine 子类 (.h):
typedef void (^DualResponseBlock)(id ResponseJson, NSError *);
-(MKNetworkOperation*) RequestWithURI:(NSString *) URI
withHandler:(DualResponseBlock)ResponseBlock;
MKNetworkEngine 子类 (.m):
-(MKNetworkOperation *)RequestWithURI:(NSString *)URI
withHandler:(DualResponseBlock)ResponseBlock {
MKNetworkOperation *op = [self operationWithPath:HubAPI(URI)
params:nil
httpMethod:@"GET"];
if(![self isReachable]) {
DLog(@"Unable to connect to %@ - Reachability is %d", HubAPI(URI), [self isReachable]);
}
[op addCompletionHandler:^(MKNetworkOperation *completedOperation) {
[completedOperation responseJSONWithCompletionHandler:^(id jsonObject) {
ResponseBlock(jsonObject, nil);
}];
} errorHandler:^(MKNetworkOperation *errorOp, NSError *error) {
[errorOp responseJSONWithCompletionHandler:^(id jsonObject) {
NSMutableDictionary *errorDetails = [NSMutableDictionary dictionary];
NSDictionary *errorResponse = [jsonObject objectForKey:@"error"];
[errorDetails setValue:[errorResponse objectForKey:@"message"] forKey:NSLocalizedDescriptionKey];
NSError *error = [NSError errorWithDomain:kNSErrorDomain code:[[errorResponse objectForKey:@"code"] intValue] userInfo:errorDetails];
ResponseBlock(nil, error);
}];
}];
[self enqueueOperation:op];
return op;
}
带有 UITableView (.h) 的 ViewController:
@interface WishlistViewController : UITableViewController <NSObject, UITableViewDelegate, UITableViewDataSource, UIActionSheetDelegate> {
NSMutableArray *wishlist;
}
@property (nonatomic, retain) IBOutlet UITableView *wishlistTableView;
带有 UITableView (-(void)viewDidLoad) (.m) 的 ViewController:
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
[app.hubEngine RequestWithURI:@"wishlist" withHandler:^(id responseJson, NSError *responseError) {
if(responseJson != nil) {
wishlist = [[NSMutableArray alloc] initWithObjects:[responseJson mutableCopy], nil];
[app.hubEngine RequestWithURI:@"wishlist/granted" withHandler:^(id responseJson, NSError *responseError) {
if(responseJson != nil) {
[wishlist addObject:[responseJson mutableCopy]];
[_wishlistTableView reloadData];
}
else {
DLog(@"Error: %@", [responseError localizedDescription]);
}
[MBProgressHUD hideHUDForView:self.view animated:YES];
}];
}
else {
DLog(@"Error: %@", [responseError localizedDescription]);
[MBProgressHUD hideHUDForView:self.view animated:YES];
}
}];