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对象传递AppDelegate给您的 UIViewController?如果没有,有两种方法可以做到这一点:

  1. AppDelegateUINavigationController根目录的示例应用程序):

    - (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 回答
0

错误说明了一切:您的 managedObjectContext 为零。

于 2013-07-22T02:09:28.253 回答