核心数据错误消息

时间:2013-07-22 02:07:48

标签: ios objective-c cocoa-touch

我创建了一个名为:"运动员"。

的核心数据实体

以下是我收到的错误:

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];

delegate.h

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

delegate.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];
}

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您是否已将managedObjectContext对象从AppDelegate正确传递到UIViewController?如果没有,有两种方法可以做到这一点:

  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];
        ...
    }