1

我正在尝试在我的应用程序的多个视图中保存和检索数据,现在我已经保存了数据,并且我可以检索该数据,只要我在 AppDelegate 中,但我已经向应用程序添加了另一个视图,我想在哪里检索和显示新存储的数据,但我不确定如何从另一个视图中访问核心数据,我该如何实现呢?

这是我到目前为止所拥有的,

AppDelegate.m:

// store the data
AppDelegate *app = [UIApplication sharedApplication].delegate;
STUDENT *std = (STUDENT *)[NSEntityDescription insertNewObjectForEntityForName:@"STUDENT" inManagedObjectContext:app.managedObjectContext];
[std setName:@"John"];
[std setNumber:[NSNumber numberWithInteger:1]];
[std setPlace:@"USA"];
[app.managedObjectContext save:nil];

// read the data
NSFetchRequest *req = [[NSFetchRequest alloc]init];
[req setEntity:[NSEntityDescription entityForName:@"STUDENT" inManagedObjectContext:app.managedObjectContext]];
[req setPredicate:[NSPredicate predicateWithFormat:@"name == %@", @"John"]];
STUDENT *stud = [[app.managedObjectContext executeFetchRequest:req error:nil] lastObject];

NSLog(@"%@",stud);

NSLog 输出你所期望的,

<STUDENT: 0x518b860> (entity: STUDENT; id: 0x518e0a0 <x-coredata://5A6AC621-11C1-4857-82BF-9BEEF258B171/STUDENT/p10> ; data: {
    name = John;
    number = 1;
    place = USA;
})

我想从中访问数据的另一个视图控制器名为FirstViewController.m/.h/.xib,我对 Objective C 很陌生。

4

2 回答 2

1

应用程序委托是一种单例,因此您应该能够从任何视图访问它

MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];

从那里你可以调用任何你想要的方法来检索和存储数据。

关于将核心数据堆栈保存在何处以通过应用程序访问存在各种问题,这里是其中之一。丹尼尔

于 2012-09-27T14:39:05.700 回答
1

您需要导入 appDelegate 的标头。您将使用它来访问 appDelegate 的托管对象上下文。您使用该上下文来获取您需要获取的信息。您还需要导入实体的类表示的标题。进行提取和插入是相同的过程。您可能还想查看NSFetchedResultsController文档以帮助您使用 tableViews 等。

于 2012-09-27T14:55:50.687 回答