3

在 iOS6 应用程序中,我使用 CoreData 从 DB 获取 NSManagedObjects 并将它们显示在 tableViewCell 中。我的问题是,与初始滚动位置之外的单元格对应的所有对象都处于故障状态并且不会恢复活力。我看不到我的错误。

fetchRequest.returnsObjectsAsFaults = 否;有帮助,但我想要一个干净的解决方案。

这是代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"ContactsCell";
    ContactsCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    Contact *contact = [self.contacts objectAtIndex:indexPath.row];

    //here some contacts are faulted. contact.name is null if I fetch it

    [cell setContactData:contact];

    return cell;
}

这是我获取的方式(使用 Restkit 0.10.3):

 NSFetchRequest *fetchRequest = [Contact fetchRequest];
    fetchRequest.sortDescriptors = [self sortDescriptors];
    fetchRequest.returnsObjectsAsFaults = NO;
    return [Contact objectsWithFetchRequest:fetchRequest];
4

1 回答 1

0

Ok I never really used your approach so I won't say that it is wrong, but I'll say that it is strange. I guess that Contact is a subclass of NSManagedObject, and I can believe that it knows of the fetch request which which he was originally fetched, and that he knows of the context from which he was fetched, but only after he was already fetched. I really don't see how could he know of those things if he never before was fetched from the persistent store. So I recommend U use classic executeFetch or fetchedResultsController to populate your tableView.

NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init]; 
[context setPersistentStoreCoordinator:persistentStoreCoordinator];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Contact" inManagedObjectContext:context];
fetchRequest.entity = entity;
fetchRequest.sortDescriptors = [self sortDescriptors];
NSArray *array = [context executeFetchRequest:fetchRequest error:&error];
return array;

Try it, hope it helps

于 2013-11-28T13:38:53.003 回答