0

这是我的核心数据结构

实体 -类别

Attr - Id (NSString)主键名称(NSString)

实体 -产品

Attr - Id (NSString), name (NSString), parentCategoryId (NSString)外键,....

从上面可以看出,Category 中的 Id指向Product 中的 parentCategoryId

在这种情况下,我想使用与产品中相关parentCatrgoryId关联的类别中的名称作为 UITableView 的部分名称。(我在 fetchrequest 中使用 @"parentCategoryId" 作为 NSSortDescriptors 的键)但是parentCatrgoryId只是字母数字文本。

如何将字母数字文本(即parentCatrgoryId 从产品解码为类别名称)

编辑

这就是我所做的及其工作。但我想问的是我所做的是否有效。

我添加了一个名为parentCategoryIdName的属性,并通过计算一些简单的操作来使用它来存储确切的名称。

.h 文件

@property (nonatomic, retain) NSMutableArray *categoryArr;
@property (nonatomic, retain) NSMutableArray *productArr;

.m 文件

   NSEntityDescription *entity = [NSEntityDescription entityForName:@"Category" inManagedObjectContext:self.MOContext];
    // Setup the fetch request
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entity];
    //    [request setPredicate:[NSCompoundPredicate andPredicateWithSubpredicates:subpredicates]];

    NSError *error;
    NSMutableArray *mutableFetchResults = [[self.MOContext executeFetchRequest:request error:&error] mutableCopy];
    [self setCategoryArr: mutableFetchResults];

    NSEntityDescription *entity2 = [NSEntityDescription entityForName:@"Product" inManagedObjectContext:self.MOContext];
    // Setup the fetch request
    NSFetchRequest *request2 = [[NSFetchRequest alloc] init];
    [request2 setEntity:entity2];
    //    [request2 setPredicate:[NSPredicate predicateWithFormat:@""]];
    NSError *error2;
    NSMutableArray *mutableFetchResults2 = [[self.MOContext executeFetchRequest:request2 error:&error2] mutableCopy];
    [self setProductArr: mutableFetchResults2];

将数据插入数据库

    for (int i=0; i< [self.productArr count]; i++) {
        Product *productEnt = [self.productArr objectAtIndex:i];
        NSManagedObjectContext *context = self.MOContext;

            for (int j=0; j<self.categoryArr.count; j++) {
                Category *categroy = [self.categoryArr objectAtIndex:j];
                if ([categroy.objectId isEqualToString:productEnt.parentCategoryId]) {
                    [productEnt setParentCategoryIdName:categroy.name];
                }

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

1 回答 1

0

回顾一下:
根据我的收集,您需要 id/name 来形成部分并将其显示在部分的标题中。

您的解决方案将是有效的 IMO,但它应该是最后的手段:

想法:当您必须返回 titleForSectionAtIndex 时,我会从 categoryId JIT 中获取 categoryName:

或者如果这太慢了。

重新加载结果时获取所有部分名称。

=> 不要将它们保存在数据库中并重复数据

如果你发现它真的太慢了​​,那么以这种方式对你的数据进行非规范化是很好的 IMO(它应该是最后一个要考虑的解决方案)

于 2012-12-04T08:59:24.923 回答