UITextField不会将文本保存到CoreData中

时间:2013-03-15 00:01:56

标签: ios objective-c core-data uitextfield

此UITextField以编程方式创建,并驻留在自定义UITableViewCell中。 UITableViewCell也是UITextField的委托,并实现<UITextFieldDelegate>协议。一切似乎工作得很好,除了当我重新加载应用程序时,没有任何文本保存在CoreData中。我试图让TableViewController成为这个类的委托,但它似乎不起作用,并且事实上使用发送到实例错误的无法识别的选择器崩溃了应用程序。

以下是我的textFieldDidEndEditing方法的代码:

- (void)textFieldDidEndEditing:(UITextField *)textField {

    Parts *item ; // the NSManagedObject

    item.itemTitle = _itemLabel.text; //_itemLabel is a custom UITextField Class, and itemTitle is a string attribute of the NSManagedObject


    NSError *error;
    [item.managedObjectContext save:&error];
    if (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();
    }

}

这是创建UITextField的自定义init方法的一部分:

_itemLabel = [[TehdaLabel alloc] initWithFrame:CGRectNull];
    _itemLabel.textColor = [UIColor blackColor];
    _itemLabel.font = [UIFont fontWithName:@"Helvetica" size:12];
    _itemLabel.backgroundColor = [UIColor clearColor];
    _itemLabel.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _itemLabel.returnKeyType = UIReturnKeyDone;
    _itemLabel.placeholder = @"Type some stuff here!";
    _itemLabel.delegate = self;
    [self addSubview:_itemLabel];

其他一切正常,保存CoreData中的文本只是拒绝为我工作。

编辑:我的TableViewController中的insertObject方法

NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
Parts *item = [NSEntityDescription insertNewObjectForEntityForName:@"Parts" inManagedObjectContext:context];

    MCSwipeTableViewCell *editCell;
    for (MCSwipeTableViewCell *cell in [self.tableView visibleCells]){
        if (cell.itemLabel.text == item.itemTitle) {
        //if (cell.itemLabel.text == item.itemTitle) {
            editCell = cell;
            break;
        }
    }
    editCell.itemLabel.text = item.itemTitle;
    [editCell.itemLabel becomeFirstResponder];

    [item setValue:[NSDate date] forKey:@"itemDate"];

    // 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();
    }

2 个答案:

答案 0 :(得分:1)

您未将实体“部件”插入CoreData。

Parts *item = [NSEntityDescription insertNewObjectForEntityForName:@"Parts"
                                              inManagedObjectContext:managedObjectContext];

现在它会保存它......

答案 1 :(得分:0)

你没有初始化项目,它是一个零对象。