1

Core Data も使用して、空の Xcode テンプレートでアプリケーションを作成しました。

Xcode は、App Delegate で ManagedObjectModel、ManagedObjectCONtex、および PersistenStoreCoordinator を自動的に生成します。

物事をきれいに保つために、ManagedObjectContext を MainVieController に渡し、それを tableViewController にも渡します (MainViewController は、TableViewController を含む TabBarViewController です)。

それは私がやった方法ですが、うまくいかないようです:

アプリ デリゲート

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

  MasterViewController *masterViewController = [[MasterViewController alloc]initWithNibName:@"MasterViewController" bundle:nil];
  [masterViewController setManagedObjectContex:_managedObjectContext];

  [self.window setRootViewController:masterViewController];
  self.window.backgroundColor = [UIColor whiteColor];
  [self.window makeKeyAndVisible];
  return YES;
}

MasterViewController

- (void)viewDidLoad
 {
  [super viewDidLoad];
  TableIngredientsViewController *tableIngredientVC = [[TableIngredientsViewController alloc]init];
  [tableIngredientVC setManagedObjectContex:_managedObjectContex];
  tableIngredientVC.fetchedResultController = _fetchedResultController;

  TablePizzasViewController *tablePizzaVC = [[TablePizzasViewController alloc]init];
  tablePizzaVC.managedObjectContex =  _managedObjectContex;
  tablePizzaVC.fetchedResultController = _fetchedResultController;

  UINavigationController *ingredientNavController = [[UINavigationController alloc]initWithRootViewController:tableIngredientVC];
  UINavigationController *pizzaNavController = [[UINavigationController alloc]initWithRootViewController:tablePizzaVC];
 [self setViewControllers:@[pizzaNavController, ingredientNavController]];
}

これは私が得るエラーです、managedObjectContext が nill のように見えます:

 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'Ingredient''
4

2 に答える 2

1

メモリが機能する場合、Core Data テンプレートは、必要なさまざまなオブジェクト (MOC を含む) のアクセサー メソッドを作成します。バッキング iVar _managedObjectContext にアクセスしているため、これらのアクセサー メソッドは呼び出されません。-managedObjectContextAppDelegateのアクセサ メソッドを介して取得してみてください。

于 2013-09-04T15:48:01.760 に答える
1

まず、前述のように、iVar の代わりに getter を使用する必要があります。

第 2 に、viewDidLoad が呼び出されたときに MOC が既に設定されていると想定することはできません。

MOC を手渡すことが推奨される方法であることは承知していますが、これはほとんどの場合、事態を非常に複雑にします。ただし、親コンテキストと子コンテキストを使用したより複雑なセットアップがある場合は必要です。

すべての viewController で 1 つのコンテキストのみを使用している場合は、実際に必要なときにデリゲートから取得する必要があります。

#import "AppDelegate.h"
[...]
- (void) methodThatNeedsToAccessTheMOC {
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *moc = myDelegate.managedObjectContext;
}
于 2013-09-05T08:57:16.660 に答える