【问题标题】:How can I access core data across multiple views?如何跨多个视图访问核心数据?
【发布时间】:2012-09-27 22:55:50
【问题描述】:

我正在尝试在我的应用程序的多个视图中保存和检索数据,现在我已经保存了数据,并且我可以检索该数据,只要我在 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 很陌生。

【问题讨论】:

    标签: objective-c ios core-data


    【解决方案1】:

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

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

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-08-04
        • 1970-01-01
        • 2014-02-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多