ios - 将 UISegmentedControl 的结果添加到核心数据实体中的属性

标签 ios core-data tableview uisegmentedcontrol

我的第一份基本申请进展顺利;我对应用程序开发还很陌生,但已经研究了很长一段时间。我试图找到这个问题的答案,这个问题对我来说没有意义。

我有一个 UITableViewController,它有一个指向 ModalViewController 的加号按钮;这要求用户用文本填写 3 个字段并选择“购买或出售”,我在 UI 中将其设置为 UISegmentedController,第一个按钮显示“购买”,第二个按钮显示“卖”。

用于添加三个文本字段的值的类包含以下代码,当我单击“保存”时,它返回到 UITableView 并显示键入的内容。

我想将单元格设置为一种颜色用于购买,一种颜色用于出售。我可以使用 cellForRow 等轻松地做到这一点。问题是数据模型和我需要帮助的代码。

我有一个包含以下实体的数据模型:

  • 交易、人物、场合和金额

交易与人、场合、金额有关。它还有一个“status”属性,它是 UISegmentedControl 的结果。

我的第一个问题是将其设置为什么类型? bool 值?

接下来,我可以/应该使用什么样的代码从用户那里获取该值并将其添加到数据库中?

这是文本字段的当前保存方法:

- (IBAction)save:(id)sender
{
    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"];    
    NSError *error = nil;
    if (![context save:&error])
    {
        NSLog(@"Can't save! %@ %@", error, [error localizedDescription]);

    }
    [self dismissViewControllerAnimated:YES completion:nil];   
}

如有任何帮助,我们将不胜感激!

最佳答案

What type do I set this to be is my first question? BOOL?

如果只有两个选项,您可以使用 bool 值。如果您这样做,我建议将其名称更改为比 status 更能说明问题的名称,例如 wasBought。在我看来,使用枚举会更好,如 this answer .

Next, what kind of code can/should I use to get that value from the user and add it to the database?

你可以这样做:

[transaction setValue:@(self.segmentedControl.selectedSegmentIndex == 0) forKey:@"wasBought"];

您可能还想阅读有关 subclassing NSManagedObject's (section "Custom Managed Object Classes") 的内容.

关于ios - 将 UISegmentedControl 的结果添加到核心数据实体中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19363027/

相关文章:

ios - 展开和折叠部分

ios - 从 CoreData 关系中获取错误实体的对象

ios - 使用 To One 类型保存托管对象

java - 将字符串转换为 ObservableValue<String>

ios - tableview 为零并且应用程序崩溃 ios xcode

ios - 当应用程序处于前台时,UILocalNotification 不播放声音

ios - MagicalRecord 示例应用程序无法在 Xcode 7 中编译

ios - 在运行时动态创建核心数据模型

ios - UITableView 部分中的 NSDates 不反射(reflect)来自 UIDatePicker 的日期

c++ - 将 TableView 中的 CheckBox 选中状态绑定(bind)到自定义模型属性