我认为答案很简单,也许我错过了一些重要的东西!我可以插入一个新对象,我可以从 managerObjectContext 中删除一个对象,我可以通过它的 ID 访问该对象,但我不明白如何更改它!
我的代码很简单:
- (NSManagedObjectContext *)managedObjectContext {
return [(CalcAppDelegate*)[[UIApplication sharedApplication]delegate] managedObjectContext];}
- (void)viewDidLoad {
[super viewDidLoad];
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Materials"];
fetchRequest.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"created" ascending:YES]];
list = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];
self.navigationItem.rightBarButtonItem = self.editButtonItem;
[tbl reloadData];}
我将数据传递给另一个 ViewController
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:@"MatListToDetailSegue"]) {
MaterialsDetailViewController *detailMaterial = segue.destinationViewController;
detailMaterial.material = [list objectAtIndex:tbl.indexPathForSelectedRow.row];
detailMaterial.managedObjectId = [[list objectAtIndex:tbl.indexPathForSelectedRow.row] objectID];
}
我想将此 managedObject 保存在 managedObjectContext 中并提交 managedObjectContext ,但我在 SQLite 文件中没有任何更改!
- (IBAction)saveBtn:(id)sender {
material.matName = editMaterialName.text;
material.matWidth = [NSNumber numberWithInt:300];
material.matPrice = [NSNumber numberWithInt:300];
[self.managedObjectContext save:nil];
[self.navigationController popViewControllerAnimated:YES];}
由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“+entityForName:nil 不是搜索实体名称“材料”的合法 NSManagedObjectContext 参数
哇!谢谢你的答案不同马赫!我解决了这个问题。
我需要:从方法中删除它 -(IBAction)saveBtn
material = (Materials *)[NSEntityDescription entityForName:@"Materials" inManagedObjectContext:managedObjectContext];
并更改 [self.managedObjectContext save:nil];
NSError *error = nil;
if (![self.managedObjectContext save:&error]) {
}
感谢您提前回复!!!