0

「Athlete」という名前のコア データ エンティティを作成しました。

これが私が得ているエラーです:

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

これは、それが壊れている行です。

Athlete *detail = [NSEntityDescription insertNewObjectForEntityForName:@"Athlete" inManagedObjectContext:context];

デリゲート.h

@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;

デリゲート.m

-(void)createData{

    NSManagedObjectContext *context = [self managedObjectContext];

    Athlete *detail = [NSEntityDescription insertNewObjectForEntityForName:@"Athlete" inManagedObjectContext:context];

    detail.first = @"Joe";

    detail.last = @"Pastrami";

    detail.phone = @"(123)456-7891";

    NSError *error;

    if(![context save:&error]){
        NSLog(@"Error :(");
    }

    NSFetchRequest *request = [[NSFetchRequest alloc] init];

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Athlete" inManagedObjectContext:context];

    [request setEntity:entity];

    NSArray *arr = [context executeFetchRequest:request error:&error];

    for (Athlete *ath in arr){
        NSLog(@"Name %@", ath.first);
    }

}



- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [self createData];
}
4

2 に答える 2

0

エラーはすべてを示しています: あなたの managedObjectContext は nil です。

于 2013-07-22T02:09:28.253 に答える
0

managedObjectContextオブジェクトを からAppDelegateに 正しく渡しましたUIViewControllerか? そうでない場合、これを行う2つの方法:

  1. から(ルートでのAppDelegateサンプルアプリ):UINavigationController

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        NSManagedObjectContext *context = [self managedObjectContext];
    
        UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController.navigationController;
        YourViewController *yourViewController = (SearchViewController *)navigationController.topViewController;
        yourViewController.managedObjectContext = self.managedObjectContext;
        ...
    }
    
  2. からYourViewController:

    #import AppDelegate.h
    ...
    @synthesize managedObjectContext;
    
    - (void)viewDidLoad
        AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
        managedObjectContext = [appDelegate managedObjectContext];
        ...
    }
    
于 2013-07-22T04:38:55.140 に答える