アプリケーション全体の複数のビュー内でデータを保存および取得しようとしています。現在、データを保存しています。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 は初めてです。