我正在学习如何使用 Core Data。我有一个应用程序可以填充标记为用户的实体的所有变量。然后我将这些用户加载到一个表中。此时可以选择用户并将其推送到新的 View Controller ,此时我生成所选用户的 PDF 文件。所以我想我误解了我必须传递给 View Controller 的内容,以便它访问表中选择的核心数据。这是我的 TableView Controller 中的内容。
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self.spinner startAnimating];
ReportPDFViewController *reviewViewController = [[ReportPDFViewController alloc] init];
reviewViewController.userInfo = [[self.fetchedResultsController fetchedObjects] objectAtIndex:indexPath.row];
[self.navigationController pushViewController:reviewViewController animated:YES];
}
然后下一个 View 说明了这一点
- (void)viewDidLoad
{
[super viewDidLoad];
UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithTitle:@"Email PDF"
style:UIBarButtonItemStylePlain
target:self
action:@selector(emailPDF)];
self.navigationItem.rightBarButtonItem = barButton;
TrafficSignalProAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
context = [appDelegate managedObjectContext];
// Do any additional setup after loading the view.
NSEntityDescription *entitydesc = [NSEntityDescription entityForName:@"User" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entitydesc];
NSError *error;
NSArray *matchingData = [userInfo executeFetchRequest:request error:&error];
NSString *Intersection;
NSString *currentDay;
for (NSManagedObject *obj in matchingData) {
Intersection = sendIntersection;
currentDay = sendDate;
}
NSString* fileName = [self getPDFFileName];
[PDFRenderer drawPDF:fileName intersectionSearch:Intersection dateSearch:currentDay];
[self showPDFFile];
self.navigationItem.title = @"Report";
}
所以我试图将所选行的 NSManagedObjectContext 传递给然后加载。在那之后我真的迷路了。我不确定传递托管对象上下文是否正确,如果正确,我不知道 ReportPDFViewController 中的代码有什么问题。我已经浏览了我能找到的所有教程。我的编程背景有限,因此非常感谢任何帮助。
最佳答案
reviewViewController.userInfo = [[self.fetchedResultsController fetchedObjects] objectAtIndex:indexPath.row];
这会将 userInfo 设置为 NSManagedObject(或子类)类型的对象。
NSArray *matchingData = [userInfo executeFetchRequest:request error:&error];
这是将 userInfo 用作 NSManagedObjectContext。我想你会在这里遇到无效的选择器错误。
userInfo 属性的实际类型是什么?应该是 NSManagedObject。
您不需要在 viewDidLoad
中执行获取请求。核心数据不是数据库。您并不总是需要在每次需要某些信息时都执行获取请求。一旦你已经有了一个托管对象,你就可以在没有获取请求的情况下获取与其相关的信息。如果您为其设置了自定义类,则几乎可以将其视为常规的 Objective-C 对象。
for (NSManagedObject *obj in matchingData) {
Intersection = sendIntersection;
currentDay = sendDate;
}
这段代码毫无意义。您正在循环,但每次都为变量分配相同的值。我不知道该值是什么,因为 sendIntersection
和 sendDate
在您发布的代码中没有被引用。无论如何,您根本没有使用提取请求的结果。
我将对您需要做什么进行大胆的猜测:
Intersection = [userInfo valueForKey:@"intersection"];
currentDay = [userInfo valueForKey:@"date"];
这完全是猜测,因为我不知道你的数据模型是什么。不需要循环,因为您只需要一个用户对象。
关于ios - 如何传递与表中选定行对应的核心数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17054463/