【问题标题】:Assigning different entities to different prototype cells将不同的实体分配给不同的原型单元
【发布时间】:2014-08-02 20:17:22
【问题描述】:

我正在 Xcode 上制作一个 coredata 应用程序。我有几个实体,它们都使用自己的原型单元格样式在自己的表格中填充单元格。我想查看一个主表上的所有实体,并发送每个实体以填充其匹配的单元格。

我认为最好的方法是创建一个抽象实体并使用 if 语句为每个实体声明单元标识符。我可能是错的,因为它还没有奏效。这是我所拥有的:

在 viewDidLoad 中:

NSEntityDescription *entityDescription = [NSEntityDescription
                                          entityForName:@"MyAbstractEntity" inManagedObjectContext:_managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];

[request setEntity:entityDescription];

关系在数据模型中建立。这是试图识别子实体的表:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

NSString *identifier;

if ([NSEntityDescription entityForName:@“Animals” inManagedObjectContext:_managedObjectContext])
{
    identifier = @“AnimalsCell";


    AnimalsCell *animalsView = (AnimalsCell *)[tableView dequeueReusableCellWithIdentifier:@"AnimalsCell" forIndexPath:indexPath];

    Animals *animals = (Animals *)[reportArray objectAtIndex:indexPath.row];
    animalsView.descriptionTextField.text = [animals description];
    return animalsView;
}

if ([NSEntityDescription entityForName:@“Plants” inManagedObjectContext:_managedObjectContext])
{
    identifier = @“PlantsCell";


    PlantsCell *animalsView = (PlantsCell *)[tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];



    Plants *plants = (Plants *)[reportArray objectAtIndex:indexPath.row];
    plantsView.flowerTextField.text = [plants flowerDetail];
    return plantsView;
}
return 0;
}

如果我输入动物,它会显示在概览表中。如果我输入植物,它会崩溃,因为它试图将植物数据放入动物细胞中,这意味着我的标识符 if 语句无法正常工作。这是我第一次尝试显示来自多个实体的数据,而且我从未使用过抽象实体,所以我可能做错了。非常感谢,伙计们!

【问题讨论】:

    标签: objective-c uitableview core-data entity fetch


    【解决方案1】:
    if ([NSEntityDescription entityForName:@"Animals" inManagedObjectContext:_managedObjectContext])
    

    始终为真,因为 if 语句中的条件返回实体描述 那不是nil。该代码无法识别当前对象的实体 显示出来。

    您可以做的是比较实际对象的实体名称:

    MyAbstractEntity *object = [reportArray objectAtIndex:indexPath.row];
    NSString *entityName = object.entity.name;
    if ([entityName isEqualToString:@"Animals"]) {
       Animals *animals = (Animals *)object;
       ...
    } else if ([entityName isEqualToString:@"Plants"]) {
       Plants *plants = (Plants *)object;
       ...
    } else {
       // What ???
    }
    

    【讨论】:

    • 有效!非常感谢你,非常感谢。这是有道理的,并在几分钟内准确地解决了我的问题。
    • @user3754137:不客气。 - 请注意,使用抽象父实体也有缺点:Core Data 然后为父实体及其所有子实体使用 single SQLite 表。这需要更多空间,而且效率可能会更低。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多