NSFetchedResultsController不显示关系中添加的最新项目

时间:2015-10-03 15:30:59

标签: ios objective-c core-data

我正在尝试使用UITableViewNSFetchedResultsController中显示项目但是当我从后台线程添加项目时,tableview不会显示更改,直到我返回到其他屏幕再来。

我还发现如果我在[_fetchedResultsController performFetch:&error];方法中调用contextChanged:,那么它会在表格中显示更新内容。

现在问题是为什么它本身没有显示新添加的项目。

- (void)contextChanged:(NSNotification*)notification
{
    if ([notification object] == [self managedObjectContext])
        return;

    if (![NSThread isMainThread])
    {
        [self performSelectorOnMainThread:@selector(contextChanged:) withObject:notification waitUntilDone:YES];
        return;
    }

    if (self.managedObjectContext!=nil)
    {
        [[self managedObjectContext] mergeChangesFromContextDidSaveNotification:notification];
    }
}

----------


- (NSFetchedResultsController *)fetchedResultsController
{
    if (_fetchedResultsController != nil)
    {
        return _fetchedResultsController;
    }

    NSString *userId=[Shared getLoginUserId];
    if (userId==nil || [userId isEqualToString:@""])
    {
        userId=@"0";
    }

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription
                                   entityForName:@"WhatNext" inManagedObjectContext:_managedObjectContext];
    [fetchRequest setEntity:entity];

     NSPredicate *predicate=[NSPredicate predicateWithFormat:@"SUBQUERY(selectedByUser,$x,$x.user_id == %@).@count > 0", [[Shared getLoginUserIdElseZero] toNSNumber]];

    NSLog(@"todo Predicate -- %@",predicate);
    [fetchRequest setPredicate:predicate];

    //    NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"localOrderNo" ascending:YES];
    NSSortDescriptor *sort2 = [[NSSortDescriptor alloc] initWithKey:@"todoFavoritesOrderNo" ascending:YES];

    [fetchRequest setSortDescriptors:@[sort2]];
    [fetchRequest setFetchBatchSize:20];

    [NSFetchedResultsController deleteCacheWithName:kToDoCacheName];
    NSFetchedResultsController *theFetchedResultsController =
    [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                        managedObjectContext:_managedObjectContext sectionNameKeyPath:nil
                                                   cacheName:nil];

    self.fetchedResultsController = theFetchedResultsController;
    _fetchedResultsController.delegate = self;

    return _fetchedResultsController;
}

enter image description here

0 个答案:

没有答案