FetchedResultsController-问题

时间:2011-09-24 03:02:56

标签: iphone objective-c cocoa-touch ipad

我遇到了问题,这让我发疯了。我想这应该很容易解决,但我不明白......

我正在尝试使用fetchedResultsController设置tableview,但由于某种原因,frc返回的section-count为零。这是我的frc代码:

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

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

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Kundendaten" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];

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

    [fetchRequest setSortDescriptors:sortDescriptors];

    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"Kundenname" cacheName:@"Root"];
    aFetchedResultsController.delegate = self;
    self._fetchedResultsController = aFetchedResultsController;

    [aFetchedResultsController release];
    [fetchRequest release];
    [sortDescriptor release];
    [sortDescriptors release];

    return _fetchedResultsController;
}

在这里,我试图获得节数:

int count = [[[self fetchedResultsController] sections] count];

//此时count-variable为0.以下只是为了证明,我的moc不为空...即使我将sectionNameKeyPath设置为nil,它也会返回0。

    NSEntityDescription *entityDescription = [NSEntityDescription
                                              entityForName:@"Kundendaten" inManagedObjectContext:self.managedObjectContext];
    NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
    [request setEntity:entityDescription];

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
                                        initWithKey:@"Kundenname" ascending:YES];
    [request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
    [sortDescriptor release];

    NSError *error = nil;
    NSArray *array = [self.managedObjectContext executeFetchRequest:request error:&error];
    count = [array count];

    return count;

在这种情况下,计数是5 ...

有人看到问题在哪里吗?

THX

1 个答案:

答案 0 :(得分:2)

好吧,看起来你已经很好地设置了fetch,但是你应该真的应该去抓取....

NSError *error = nil;
if (![aFetchedResultsController performFetch:&error]) {
     NSLog(@"Bad Fetch %@", error);
 }