2012-09-27 58 views
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,我很安靜的新目標C.

回答

1

的應用程序委託是各種各樣的單,所以你應該能夠從做

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

從那裏,你可以打電話給你想要它的任何方法來檢索任何視圖訪問並存儲數據。

有關於何處保持核心數據堆棧可以通過應用程序訪問的各種問題,here就是其中之一。 Daniel

+0

謝謝,這個伎倆! :) – Odyss3us

1

您需要導入appDelegate的標頭。您將使用它來訪問appDelegate的託管對象上下文。您可以使用該上下文獲取您需要獲取的信息。您還需要導入實體的類表示的標題。提取和插入是相同的過程。您可能還想檢查NSFetchedResultsController文檔以幫助您使用tableViews等。