到目前为止,我有一个工作应用程序,它基本上包括以下内容:
使用核心数据,我有 1 个带有添加按钮的表视图控制器,它以模态方式调用一个新的视图控制器,提示用户将文本添加到三个字段中。还有一个选择字段,用户必须在“购买”和“出售”之间进行选择。当用户单击保存时,该条目将作为字幕单元格添加到表格视图控制器中,并填写了信息。它现在运行良好,没有买卖方面。
我想做的只是将表格视图单元格的颜色更改为绿色表示已售出,红色表示已买入。因此,当用户添加信息时,他们填写必填字段并选择买入或卖出,然后单击保存时,表格视图单元格显示每个条目的绿色或红色。
我在当前 TableViewController 中添加了 tableView 数据源和委托方法。有了这个,我基本上正在研究一个“交易”实体并获取与其他实体的关系。“状态”(已购买/已售)也在与交易实体相关的实体中,在它自己的称为购买的实体中。所以 Transaction 有一个称为 status.action 的关系(action 是 Transaction 的逆属性)。
这是到目前为止 TableView 的代码:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.transactions.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Persons";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSManagedObject *transaction = [self.transactions objectAtIndex:indexPath.row];
[cell.textLabel setText:[NSString stringWithFormat:@"%@ %@", [transaction valueForKeyPath:@"whoBy.name"], [transaction valueForKeyPath:@"gifting.amount"]]];
[cell.detailTextLabel setText:[NSString stringWithFormat:@"%@", [transaction valueForKeyPath:@"occasion.title"]]];
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
[self.managedObjectContext deleteObject:[self.transactions objectAtIndex:indexPath.row]];
[self.transactions removeObjectAtIndex:indexPath.row];
[self.tableView reloadData];
NSError *error = nil;
if (![self.managedObjectContext save:&error])
{
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
[self.tableView reloadData];
}
}
}
来自 Modal 的代码实际上继续进行并允许用户添加条目文本(以及选择尚未实现的 Bought/Sold),如下所示:
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *transaction = [NSEntityDescription insertNewObjectForEntityForName:@"Transaction" inManagedObjectContext:context];
NSManagedObject *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:context];
NSManagedObject *occasionEvent = [NSEntityDescription insertNewObjectForEntityForName:@"Occasion" inManagedObjectContext:context];
NSManagedObject *amountType = [NSEntityDescription insertNewObjectForEntityForName:@"Gift" inManagedObjectContext:context];
[person setValue:self.nameTextField.text forKey:@"name"];
[occasionEvent setValue:self.occasionTextField.text forKey:@"title"];
[amountType setValue:self.amountTextField.text forKey:@"amount"];
[transaction setValue:person forKey:@"whoBy"];
[transaction setValue:occasionEvent forKey:@"occasion"];
[transaction setValue:amountType forKey:@"gifting"];
任何帮助,将不胜感激。
谢谢