使用NSFetchedResultsController初始获取始终返回空对象

时间:2015-03-12 08:31:27

标签: ios objective-c xcode nsfetchrequest

下面的代码在初始提取时没有返回任何对象,而成功提取则返回正确的对象。我也在检查vehicleManagedObjectContext,但它总是空的。

    - (NSArray *)getVehicleInfo  {
        if (vehicleManagedObjectContext == nil) {
            NSLog(@"======== Error: vehicleManagedObjectContext is empty"); 
        }

        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

        NSEntityDescription *entity = [NSEntityDescription entityForName:@"VehicleInfo" inManagedObjectContext:vehicleManagedObjectContext];
        [fetchRequest setEntity:entity];

        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"vehicleType" ascending:YES];
        NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
        [fetchRequest setSortDescriptors:sortDescriptors];

        NSFetchedResultsController *fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:vehicleManagedObjectContext sectionNameKeyPath:@"vehicleType" cacheName:nil];

        [fetchedResultsController performFetch:nil];

        NSLog(@"======== fetchedObjects : %@",[fetchedResultsController fetchedObjects]);

        if ([fetchedResultsController fetchedObjects] && [[fetchedResultsController fetchedObjects] count] > 0) {
            return [fetchedResultsController fetchedObjects];
        }

        return nil;
    }

0 个答案:

没有答案