我是创建iOS应用程序的新手。我必须快速创建一个表单应用程序,我可以从愿意填写信息的人那里存储信息。基本上只是一堆文本字段,如名称,邮件等。核心数据错误:nil不是合法的NSManagedObjectContext参数
表单填写完成后,使用这一位代码存储他们的数据:
//Save action
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Person" inManagedObjectContext: context];
NSManagedObject *newPerson = [[NSManagedObject alloc]initWithEntity:entityDesc insertIntoManagedObjectContext:context];
//Fill in values
[newPerson setValue:self.btnPrefix.titleLabel.text forKey: @"prefix"];
[newPerson setValue:self.txtFirstName.text forKey: @"firstname"];
[newPerson setValue:self.txtLastName.text forKey: @"lastname"];
[newPerson setValue:self.txtLive.text forKey: @"country"];
[newPerson setValue:self.txtMail.text forKey: @"email"];
[newPerson setValue:self.txtPhone.text forKey: @"phonenumber"];
[newPerson setValue:self.txtLinked.text forKey: @"linkedIn"];
[newPerson setValue:self.txtAbout.text forKey: @"about"];
NSError *error;
[context save:&error];
当在模拟器上执行时根本没有问题。但是,一旦在iPad上运行我得到这个错误:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'Person''
调试它就会在第一行triggerd后:
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Person" inManagedObjectContext: context];
了些研究后,我的AppDelegate包含零persistentContainer当跑设备,但在虚拟设备上运行时会填充它。所以我想问题在那里,但我找不到解决问题的方法。
- (void)viewDidLoad {
[super viewDidLoad];
AppDelegate *appdelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
context = appdelegate.persistentContainer.viewContext;
}
任何人都可以帮我吗?
错误告诉你,你的'context'参数是'nil',不一定是这种情况。你如何获得你传入的托管对象上下文对象?我假设你确保你的模型确实包含一个名为“Person”的实体,对吗? – Gero
under ** viewDidLoad **'AppDelegate * appdelegate =(AppDelegate *)[[UIApplication sharedApplication] delegate]; context = appdelegate.persistentContainer.viewContext;'。是的,我有一个包含实体Person的模型。正如我所说的,它可以在模拟器上工作,所以我想只有一件东西可以让它在物理设备上工作? – Akorna
经过一番研究后,我的Appdelegate在设备上运行时包含一个零persistentContainer,但是它在虚拟设备上运行时被填充。所以我想问题在那里,但我找不到解决问题的方法。 – Akorna