【发布时间】:2015-03-25 23:03:00
【问题描述】:
我正在尝试为多个选项卡使用 UIManagedDocument 上下文,以从我的数据库中检索和存储数据。但是,它只能在我在第一个选项卡上时检索信息。第二个和第三个选项卡不显示数据,我无法使用它们将数据插入核心数据。我使用检索到的上下文来设置通用 NSFetchController,但正如我所说,这仅适用于第一个选项卡。我做错了什么?
- (NSManagedObjectContext *)managedObjectContext {
if (_document.managedObjectContext) {
return _document.managedObjectContext;
}
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *documentsDirectory = [[fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject]; // Default location to store the document
NSString *documentName = @"ModelDocument";
NSURL *url = [documentsDirectory URLByAppendingPathComponent:documentName];
self.document = [[UIManagedDocument alloc] initWithFileURL:url];
if ([fileManager fileExistsAtPath:[url path]]) { // If already exists, open the document
[self.document openWithCompletionHandler:^(BOOL success) {
if (success) {
[self announceContextReady];
} else {
NSLog(@"Problem with database!");
}
}];
} else {
[self.document saveToURL:url forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) { // Document doesnt exist, create it
if (success) {
[self announceContextReady];
} else {
NSLog(@"Problem with saving!");
}
}];
}
return _document.managedObjectContext;
}
获取控制器(不适用于第二个或第三个选项卡):
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath {
switch (type) {
case NSFetchedResultsChangeInsert: {
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
}
case NSFetchedResultsChangeDelete: {
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
}
case NSFetchedResultsChangeUpdate: {
[self configureCell:(UITableViewCell *)[self.tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
break;
}
case NSFetchedResultsChangeMove: {
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
}
【问题讨论】:
标签: ios uimanageddocument