代码之家  ›  专栏  ›  技术社区  ›  7c9d6b001a87e497d6b96fbd4c6fdf

NSFetchedResults控制器、核心数据和线程

  •  1
  • 7c9d6b001a87e497d6b96fbd4c6fdf  · 技术社区  · 11 年前

    你好,各位飞越者

    我很难弄清楚如何在后台线程中获取NSManagedObjects,然后通过NSFetchedResultsController显示结果。

    到目前为止,这是我的代码:

           _theManagedObjectContext = [[DataManager sharedInstance] mainManagedObjectContext]; 
    
       __block NSMutableArray *objectsIDs;
    
        [[[DataManager sharedInstance] backgroundManagedObjectContext] performBlock:^{
    
            NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
            fetchRequest.entity = [NSEntityDescription entityForName:@"Ret" inManagedObjectContext:[[DataManager sharedInstance] backgroundManagedObjectContext]];
    
            NSArray *results =  [[[DataManager sharedInstance] backgroundManagedObjectContext] executeFetchRequest:fetchRequest error:nil];
    
            for (Ret *ret in results) {
                NSManagedObjectID *moID = [ret objectID];
    
                [objectsIDs addObject:moID]; 
    
                NSLog(@"%@", objectsIDs); 
            }
    
            [[[DataManager sharedInstance] mainManagedObjectContext ] performBlock:^{
    
                [self loadDishesWithObjectIDs:objectsIDs]; 
    
            }];
    
    
    
        }];
    

    首先,我在后台线程中获取所有对象,然后将NSMangeObjectID传输到主线程。

    在我的“loadDishes”方法中:

    - (void)loadDishesWithObjectIDs:(NSArray *)objectsIDs {
    
         /*
        [NSFetchedResultsController deleteCacheWithName:@"dishes"];
        self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:**???**? managedObjectContext:_theManagedObjectContext sectionNameKeyPath:nil cacheName:@"dishes"];
        _fetchedResultsController.delegate = self;
    
    
    
    
        NSError *error = nil;
    
    
        if (![_fetchedResultsController performFetch:&error]) {
            NSLog(@"Fetch Failed");
    
        }
    
    
        NSArray *theDishes = _fetchedResultsController.fetchedObjects;*/
    
    
    
    }
    

    如何通过从后台线程获取的ObjectID来显示带有NSFetchResults控制器的对象?

    提前感谢:)

    1 回复  |  直到 11 年前
        1
  •  1
  •   Paul.s    11 年前

    您需要创建一个类似于以下内容的获取请求

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    fetchRequest.entity = [NSEntityDescription entityForName:@"Ret" 
                                      inManagedObjectContext:[[DataManager sharedInstance] mainManagedObjectContext]];
    fetchRequest.predicate = [NSPredicate predicateWithFormat:@"self IN %@", objectIDs];