我是創建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