如何刷新/重新加载managedObjectContext?

时间:2015-04-15 19:55:25

标签: ios objective-c core-data

我正在开发iOS应用,我遇到managedObjectContext的问题。我正在加载一个ViewController,然后我从API请求一个对象,然后我使用Core Data将它保存到本地app数据库。我已经使用save:保存了主上下文,但是我需要刷新managedObjectContext,因为它似乎没有对象,我想渲染我添加到数据库中的这个新对象。目前,如果我重新加载此ViewController的操作,此对象就在上下文中,我可以渲染它。

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  Notification *notification = [self.fetchedResultsController objectAtIndexPath:indexPath];

  if ([notification.isRead isEqualToNumber:@NO]) {
    [self sendNotificationData:notification];
    notification.isRead = @YES;
  }

  [self insertPost:notification.notificatableId];

  Post *post = [self fetchObjectfrom:@"Post"
                   withPredicate:[NSPredicate predicateWithFormat:@"objectId == %@", notification.notificatableId]];
}

- (void)insertPost:(NSString *)postId
{

  NSDictionary *parameters = [[NSDictionary alloc] initWithObjectsAndKeys:postId, @"notification[post_id]", nil];

  [[AkdemiaAPIClient sharedClient] POST:[NSString stringWithFormat:@"/notifications/%@/get_post",postId] parameters:parameters
                        success:^(NSURLSessionDataTask *task, id JSON) {

                          [[NSUserDefaults standardUserDefaults] setBool:YES
                                                                  forKey:@"PostNotificationsDetailsNotificationName"];
                          [[NSUserDefaults standardUserDefaults] synchronize];

                          [[NSNotificationCenter defaultCenter] postNotificationName:@"PostNotificationsDetailsSucceedNotificationName"
                                                                              object:nil];

                          AkdemiaSyncEngine *syncEngine = [[AkdemiaSyncEngine alloc] init];
                          [syncEngine processJSONDataRecordsIntoCoreData:JSON forComponent:kFeed];

                          [[AkdemiaCoreDataController sharedInstance] saveBackgroundContext];
                          [[AkdemiaCoreDataController sharedInstance] saveMasterContext];

                        } failure:^(NSURLSessionDataTask *task, NSError *error) {

                          [[NSNotificationCenter defaultCenter] postNotificationName:@"PostNotificationsDetailsErrorNotificationName"
                                                                              object:nil];

                        }];
}

这是我请求对象的代码,然后我将其保存在数据库中。使用:

[[AkdemiaCoreDataController sharedInstance] saveBackgroundContext];
[[AkdemiaCoreDataController sharedInstance] saveMasterContext];

我打电话给save:方法

0 个答案:

没有答案
相关问题