我有一个独立的CoreData实体,包含大约30条记录。我定期删除记录并重新填充相关的CoreTableViewController。我的NSFetchRequest没有返回任何记录。
但是setupFetchedResultsController中完全相同的FetchRequest确实会返回记录。
我确信我错过了一些明显的东西,但还没弄清楚是什么。有什么想法吗?
- (void)eraseFetchedResults:(NSManagedObjectContext *)myContext
{
NSFetchRequest *allAthletes = [NSFetchRequest fetchRequestWithEntityName:@"ResultsForAthleteSearch"];
allAthletes.sortDescriptors = [NSArray arrayWithObject:[
NSSortDescriptor sortDescriptorWithKey:@"orderRecordsDownloaded"
ascending:YES]];
// no predicate because we want ALL the Athletes
[allAthletes setIncludesPropertyValues:YES]; //only fetch the managedObjectID
NSError * error = nil;
NSArray * athletes = [myContext executeFetchRequest:allAthletes error:&error];
NSLog(@"NSArray athletes is %d", [athletes count]);
//error handling goes here
for (NSManagedObject * athlete in athletes) {
[myContext deleteObject:athlete];
}
NSError *saveError = nil;
[myContext save:&saveError];
}
- (void)setupFetchedResultsController // attaches an NSFetchRequest to this UITableViewController
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"ResultsForAthleteSearch"];
request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"orderRecordsDownloaded" ascending:YES]];
// no predicate because we want ALL the Athletes
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:self.athleteSearchDatabase.managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
}
这是调用方法:
- (void)useDocument
{
NSLog(@"Does athleteSearchDatabase exist? %d", [[NSFileManager defaultManager] fileExistsAtPath:[self.athleteSearchDatabase.fileURL path]]);
NSString *checkName = _searchName;
if (![[NSFileManager defaultManager] fileExistsAtPath:[self.athleteSearchDatabase.fileURL path]]) {
// does not exist on disk, so create it
[self.athleteSearchDatabase saveToURL:self.athleteSearchDatabase.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
[self setupFetchedResultsController];
NSLog(@"checkName is %@ before calling fetchAthleteSearchResultsIntoDocument.",checkName);
[self fetchAthleteSearchResultsIntoDocument:self.athleteSearchDatabase whereNameIs:checkName];
}];
} else if (self.athleteSearchDatabase.documentState == UIDocumentStateClosed) {
// exists on disk, but we need to open it
[self eraseFetchedResults:self.athleteSearchDatabase.managedObjectContext];
[self.athleteSearchDatabase openWithCompletionHandler:^(BOOL success) {
[self setupFetchedResultsController];
[self fetchAthleteSearchResultsIntoDocument:self.athleteSearchDatabase whereNameIs:checkName];
}];
} else if (self.athleteSearchDatabase.documentState == UIDocumentStateNormal) {
// already open and ready to use
[self setupFetchedResultsController];
}
}
答案 0 :(得分:0)
好吧,我没弄清楚为什么这个特殊的获取请求没有返回任何记录,但是我已经使用了 Matthew Frederick's问题的解决方案here。能够覆盖记录并获得更优雅的解决方案。
如果有人有兴趣,会发布更多细节。