我何时应该使用AFNetworking初始化NSFetchedResultsController?目前我正在这样做:
[[AFHttpClient sharedClient] GET:@"/admin/stockCategories" parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
if (response.statusCode == 200) {
NSArray *results = (NSArray *)responseObject;
if ([results count] > 0) {
for (NSDictionary *obj in results) {
StockCategory *category = [StockCategory MR_createEntity];
category.name = obj[@"name"];
category.categoryId = obj[@"_id"];
category.createdDate = [NSDate dateForRFC3339DateTimeString:obj[@"createdDate"]];
[context MR_saveWithOptions:MRSaveParentContexts completion:^(BOOL success, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
[SVProgressHUD dismiss];
[self.tableView reloadData];
});
}];
}
} else {
}
}
} failure:^(NSURLSessionDataTask *task, NSError *error) {
}];
我知道通常我在将对象保存到核心数据后将执行获取请求置于成功块中。我应该这样做:
[context MR_saveWithOptions:MRSaveParentContexts completion:^(BOOL success, NSError *error) {
// add NSFetchedResultsController here ?
self.fetchedResultsController = [StockCategory MR_fetchAllSortedBy:@"createdDate" ascending:NO withPredicate:nil groupBy:nil delegate:self];
dispatch_async(dispatch_get_main_queue(), ^{
[SVProgressHUD dismiss];
[self.tableView reloadData];
});
}];
如果是这样,self.fetchedResultsController将多次初始化。我不这么认为。我目前所做的是:
- (NSFetchedResultsController *)fetchedResultsController{
if (!_fetchedResultsController) {
_fetchedResultsController = [StockCategory MR_fetchAllSortedBy:@"createdDate" ascending:NO withPredicate:nil groupBy:nil delegate:self];
}
return _fetchedResultsController;
}
但是在我的UITableViewDatasource方法中,只有numberOfRows方法可以工作,但是cell.textLabel.text是空的。但是,如果我重新启动模拟器,并评论afnetworking get方法。一切正常,对象已经保存了核心数据,NSFetchedResultsController也可以工作。