![](/img/trans.png)
[英]How to display data from Core Data database in custom TableView Cells?
[英]Saving data from tableview cells in core data
嗨,我正在尝试将数据保存到核心数据中并遇到一些麻烦...我有一个Team Entity和一个Player Entity。Team Entity与Player Entity设置为一对多关系...在我的“ NewTeamViewController”上有两个部分,第二部分是向团队中添加球员的地方。 在该部分的标题中,有一个添加新播放器的按钮...当按下该按钮时,将出现一个带有三个textField的新单元格,每个文本字段中都带有默认文本(不是占位符文本),然后将新播放器添加到MutableSet中。将被添加为团队球员。 tableview使用的是自定义单元格(这是三个textField所在的位置)
团队保存正确,但是我无法保存播放器单元格中三个文本字段中的数据。 它只是将默认文本保存在播放器的单元格中。
我不确定如何或在何处将数据从新添加的单元格提供给新添加的播放器对象。
这是一些代码...
-(void)saveButtonWasPressed {
self.team =[NSEntityDescription insertNewObjectForEntityForName:@"Team" inManagedObjectContext:self.managedObjectContext];
team.schoolName = _schoolName.text;
team.teamName = _teamName.text;
team.season = _season.text;
team.headCoach = _headCoach.text;
team.astCoach = _assistantCoach.text;
player.firstName = cell.playerFirstName.text;
player.lastName = cell.playerLastName.text;
player.number = cell.playerNumber.text;
[self.team addPlayers:_tempSet];
[self.managedObjectContext save:nil];
[self.navigationController popViewControllerAnimated:YES];
}
//////////////////////////////////////////////////////////////////////////////////////////////////
-(void)addPlayerButton {
player = (Player *)[NSEntityDescription insertNewObjectForEntityForName:@"Player"
inManagedObjectContext:self.managedObjectContext];
[_tempSet addObject:player];
[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationFade];
}
将您的NewTeamViewController
添加为每个文本字段的控件事件UIControlEventEditingChanged
的目标。 您可以在代码中( cellForRowAtIndexPath...
)或在笔尖或情节cellForRowAtIndexPath...
执行此操作。 对于每个单元格中的三个不同文本字段,我将使用不同的操作方法。 您的操作方法如下所示:
// Helper method
- (Player *)playerForTextField:(UITextField *)textField
{
NSIndexPath *indexPath = [self.tableView indexPathForCell:textField.superview];
return [_tempArray objectAtIndex:indexPath.row];
}
- (IBAction)firstNameDidChange:(UITextField *)textField
{
Player *player = [self playerForTextField:textField];
player.firstName = textField.text;
}
- (IBAction)lastNameDidChange:(UITextField *)textField
{
Player *player = [self playerForTextField:textField];
player.lastName = textField.text;
}
- (IBAction)numberDidChange:(UITextField *)textField
{
Player *player = [self playerForTextField:textField];
player.number = textField.text;
}
另外,将_tempSet
更改为_tempArray
因为知道表中播放器的顺序很有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.