ios - iOS7 中 NSFetchedResultsController 的问题?

标签 ios iphone cocoa-touch core-data

我正在使用 NSFetchedResultsController 将一些数据加载到 UITableView 中。无论我保存了多少个对象,它都只加载第一个。如果我从 UITableView 中删除那个对象并重新加载它,有时它会显示一个或多个我保存的其他对象。这是非常不可预测的。

奇怪的是我使用的代码在 iOS6 SDK 上运行良好。我知道问题出在 NSFetchedResultsController 上,因为当我使用 NSFetchRequest 发出获取请求时,返回的数据是正确的。这是代码;

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    NSError *error;

    if (![[self fetchedResultsController] performFetch:&error])
    {
        exit(-1);
    }
}

- (void)viewDidUnload
{
    self.fetchedResultsController = nil;
}

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

        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"HatInfo" inManagedObjectContext:[self.appDelegate managedObjectContext]];
        [fetchRequest setEntity:entity];

        NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"lastSaved" ascending:NO];
        [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];

        [fetchRequest setFetchBatchSize:9];
        NSArray *fetchedObjects = [[self.appDelegate managedObjectContext] executeFetchRequest:fetchRequest error:nil];
        //returns the correct amount of objects
        NSLog(@"FetchedObjects: %lu", (unsigned long)[fetchedObjects count]);

        NSFetchedResultsController *theFetchedResultsController =
        [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                            managedObjectContext:[self.appDelegate managedObjectContext] sectionNameKeyPath:nil
                                                       cacheName:@"Root"];
        self.fetchedResultsController = theFetchedResultsController;
        _fetchedResultsController.delegate = self;

        return _fetchedResultsController;

    }

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    id  sectionInfo = [[_fetchedResultsController sections] objectAtIndex:section];
    //returns the incorrect amount
    return [sectionInfo numberOfObjects];
}

最佳答案

如果您在核心数据代码的其他部分使用相同的 cacheName(例如:应用中的另一个 fetchedResultsController),就会发生这种意外行为。 您可以尝试将缓存名称更改为不同的名称或 nil,看看会发生什么。

关于ios - iOS7 中 NSFetchedResultsController 的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21803407/

相关文章:

iphone - 无法正确设置 NSURLIsExcludedFromBackupKey

ios - 如何在不解包可选值的情况下使用字符串变量

iphone - iPhone 上的图片链接不可点击

ios - UISlider 上的 resizableImageWithCapInsets 在 iOS 6 及更高版本中变形

ios - 使用 Jenkins 进行 Xcode 签名

iOS Firebase 获取值等于某物的数据

iphone - 同时插入和删除 UITableViewCell 不起作用

iphone - 多行 HUD

c# - 如何在不启动 Monotouch 播放的情况下从电影中获取缩略图

ios - 制作按钮切换方法——objective-c