1. 2 つのビューから同じ Core Data コンテキストを使用する最良の方法は何ですか?
2 つの ViewController を持つ TabBarController があります。最初に、保存する必要がある時間を記録したいと思います。2 番目には、すべてのレコードを表示する TableView があります。チュートリアルで言われたとおりに実行し、App Delegate ですべての ManagedDataContext を開始して、コントローラーに渡します。
- (void)applicationDidFinishLaunching:(UIApplication *)application {
SecondViewController *tableController = [[SecondViewController alloc] init];
tableController.managedObjectContext = [self managedObjectContext];
self.navigationController = [[UINavigationController alloc] initWithRootViewController:tableController];
[window addSubview: [self.navigationController view]];
[window makeKeyAndVisible];
}
しかし、この変数を(同じクラスでも)複数回使用すると、(ある種のnullpointer)エラーが発生します。
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'Event''
デバッグ中に、ここの managedObjectContext が null であることがわかりました。
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:managedObjectContext];
ここで何が問題なのですか?ビューへの最適なソリューションは何ですか?
シングルトンを使用することは可能ですか?
- (NSManagedObjectContext *) managedObjectContext {
if (managedObjectContext != nil) {
NSLog(@"managedObjectContext already in use. Returning instance.");
return managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator: coordinator];
}
NSLog(@"managedObjectContext nil. Returning new instance.");
return managedObjectContext;
}
2. データモデルとは異なるオブジェクトを格納できますか?
私のクラスに含まれる他のオブジェクトを保存しないようにする必要があります。保存したくない配列のように。これは可能ですか?