核心数据获取许多人

时间:2012-10-20 22:33:02

标签: iphone objective-c ios core-data

我正在尝试获取所有类别及其子类别,并将它们全部显示在表格中。我知道如何获取所有类别,但我需要获取所有子类别,并使用获取结果控制器按类别对它们进行排序。有任何建议吗?

enter image description here

3 个答案:

答案 0 :(得分:2)

您可以创建一个提取的结果控制器,用于提取 SubCategory 实体,并根据类别将它们分组:

// Fetch "SubCategory" entities:
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"SubCategory"];

// First sort descriptor for grouping the cells into sections, sorted by category name:
NSSortDescriptor *sort1 = [NSSortDescriptor sortDescriptorWithKey:@"category.name" ascending:YES];
// Second sort descriptor for sorting the cells within each section:
NSSortDescriptor *sort2 = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
request.sortDescriptors = [NSArray arrayWithObjects:sort1, sort2, nil];

self.fetchedResultsController = [[NSFetchedResultsController alloc]
                                        initWithFetchRequest:request
                                        managedObjectContext:context
                                          sectionNameKeyPath:@"category.name"
                                                   cacheName:nil];

[self.fetchedResultsController setDelegate:self];
NSError *error;
BOOL success = [self.fetchedResultsController performFetch:&error];

然后您可以使用NSFetchedResultsController Class Reference中描述的常用表格视图数据源方法。

这为您提供了一个表视图,每个类别都有一个表视图部分。

答案 1 :(得分:1)

所以,你有 fetchedResultsController.fetchedObjects

中的类别

由于每个子类别基本上都包含在类别中,您可以通过调用[Category valueForKey:@"subCategory"

来访问每个子类别

这将为您提供一个NSSet,然后您可以将其分类(到NSArray)并用作tableView的数据。

虽然它不会包含在fetchedResultsController中。

答案 2 :(得分:0)

如果您有选择,如果您愿意,也可以通过其他方式进行。

获取arrayOfCategories中的所有Category对象

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection (NSInteger)section:


{
    Category *cat = [ arrayOfCategories objectAtIndex:indexPath.row]

   if(arrayToHoldObjects.count > 0)

{

[arrayToHoldObjects removeAllObject];
}


for(Subcategory *sub in Category.subcategory)

{
   [arrayToHoldObjects addObject:sub];

}

  return arrayToHoldObjects.count;


}

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


  Category *cat = [ arrayOfCategories objectAtIndex:indexPath.row]

   if(arrayToHoldObjects.count > 0)

{

[arrayToHoldObjects removeAllObject];
}


for(Subcategory *sub in Category.subcategory)

{
   [arrayToHoldObjects addObject:sub];

}

   Subcategory *sub = [arrayToHoldObjects objectAtIndexPath.row]  

   for(int k =0 ; k < arrayToHoldObjects .count; k++)
  {

    // do what ever u like with sub  

     return cell;

   }



}
相关问题