添加到tableView时,新对象无法正确保存

时间:2013-03-03 23:16:32

标签: iphone ios objective-c cocoa-touch

我在使用UITextField获取Core Data以保存新行时遇到一些问题。这是我将对象插入表视图的方法。应该发生的是当我单击添加按钮时,应该添加一个文本字段,然后直接进入编辑模式。然后,当用户在键盘上单击完成时,文本字段应该结束编辑,然后文本字段应该将条目保存到核心数据中。

修改:已移除textFieldDidEndEditing方法中对insertNewObject:(id)sender的调用。它崩溃了应用程序

 - (void)insertNewObject:(id)sender {

NSManagedObjectContext *context = [self.fetchedResultsController     managedObjectContext]; 

TehdaItem *item = [NSEntityDescription insertNewObjectForEntityForName:@"TehdaItem" inManagedObjectContext:context];


// If appropriate, configure the new managed object.
// Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template.


// Putting the cell in edit mode
TehdaTableViewCell *editcell;
for (TehdaTableViewCell *cell in [self.tableView visibleCells]) {
    if (cell.itemLabel.text == item.itemTitle) {

        editcell = cell;

        break;
    }
}



[editcell.itemLabel becomeFirstResponder];

// The cell needs to call the method textfield did end editing so that it can save the new object into the store

// Save the context.

NSError *error = nil;
if (![context save:&error]) {
     // Replace this implementation with code to handle the error appropriately.
     // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}

}

这是我的textFieldDidEndEditing方法:

- (void)textFieldDidEndEditing:(UITextField *)textField {
TehdaTableViewCell *cell = (TehdaTableViewCell *) textField.superview.superview;
TehdaItem *item = [self.fetchedResultsController objectAtIndexPath:[self.tableView indexPathForCell:cell]];

//TehdaTableViewCell *cell;
item.itemTitle = cell.itemLabel.text;

}

不确定从哪里开始。任何帮助,将不胜感激。

感谢。

1 个答案:

答案 0 :(得分:0)

您可以使用

NSError *error;
[item.managedObjectContext save:&error];
if (error) {
// Triage the problem and respond appropriately
}
- (void)textFieldDidEndEditing:(UITextField *)textField方法中的

。但如果我是你,我会在保存对象之前做一些验证。