我目前正在尝试编写我的第一个 CoreData 项目并且非常困惑。我正在使用以下代码来设置获取的结果控制器:
- (NSFetchedResultsController *)fetchedResultsController {
if (_fetchedResultsController != nil)
return _fetchedResultsController;
Singleton *singleton = [Singleton sharedSingleton];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"MapEntity" inManagedObjectContext:[singleton managedObjectContext]];
[fetchRequest setEntity:entity];
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"sName" ascending:NO];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
[fetchRequest setFetchBatchSize:8];
// Finally check the results
NSError *error;
NSArray *fetchedObjects = [[singleton managedObjectContext] executeFetchRequest:fetchRequest error:&error];
for (MapEntity *map in fetchedObjects)
{
NSLog(@"Maps present in database: %@", map.sName);
}
NSFetchedResultsController *theFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[singleton managedObjectContext] sectionNameKeyPath:nil cacheName:@"Root"];
self.fetchedResultsController = theFetchedResultsController;
_fetchedResultsController.delegate = self;
return _fetchedResultsController;
}
我放入 NSLog 以查看 fetchRequest 是否正在查找结果,并且确实如此:
2013-01-28 11:20:14.735 WildMap_iOS[10931:16a03] Maps present in database: UK Capital Cities
2013-01-28 11:20:14.736 WildMap_iOS[10931:16a03] Maps present in database: The UK
2013-01-28 11:20:14.736 WildMap_iOS[10931:16a03] Maps present in database: Testing123
2013-01-28 11:20:14.736 WildMap_iOS[10931:16a03] Maps present in database: TestForPic
2013-01-28 11:20:14.736 WildMap_iOS[10931:16a03] Maps present in database: Scottish Map
2013-01-28 11:20:14.736 WildMap_iOS[10931:16a03] Maps present in database: Old Scotland
2013-01-28 11:20:14.736 WildMap_iOS[10931:16a03] Maps present in database: Old Scotland
2013-01-28 11:20:14.737 WildMap_iOS[10931:16a03] Maps present in database: Old Scotland
2013-01-28 11:20:14.737 WildMap_iOS[10931:16a03] Maps present in database: Field Concatination
但是,当我尝试使用我的 fetchedResultsController 来设置我的 tableView numberOfRowsInSection 时,如下所示:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
id sectionInfo = [[_fetchedResultsController sections] objectAtIndex:section];
return [sectionInfo numberOfObjects];
}
'返回 [sectionInfo numberOfObjects];' 返回 nil,即使 fetchRequest 似乎可以很好地拾取对象。
我使用这段代码很好,但是我最近向 mapEntity (iID) 添加了一个整数,它让我删除了模拟器数据,因为存储数据的结构发生了变化。在我删除数据并重新启动应用程序后,代码不再有效。
谁能帮我理解为什么会这样?我认为它不像以前那样使用命名约定,并且 fetchRequest 正在返回结果。