我创建了一个名为:"运动员"。
的核心数据实体以下是我收到的错误:
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];
}
答案 0 :(得分:0)
错误说明了一切:您的managedObjectContext为零。
答案 1 :(得分:0)
您是否已将managedObjectContext
对象从AppDelegate
正确传递到UIViewController
?如果没有,有两种方法可以做到这一点:
来自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;
...
}
来自YourViewController
:
#import AppDelegate.h
...
@synthesize managedObjectContext;
- (void)viewDidLoad
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
managedObjectContext = [appDelegate managedObjectContext];
...
}