Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/122.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 核心数据属性计数并在TableView中显示结果_Ios_Core Data_Ios5_Count_Nsfetchrequest - Fatal编程技术网

Ios 核心数据属性计数并在TableView中显示结果

Ios 核心数据属性计数并在TableView中显示结果,ios,core-data,ios5,count,nsfetchrequest,Ios,Core Data,Ios5,Count,Nsfetchrequest,我有一个名为Car的实体,它有2个属性:名称和颜色 数据库中有几辆车: 名称:本田思域 颜色:蓝色 名称:大众高尔夫 颜色:蓝色 名称:雷诺Twingo 颜色:红色 名称:雪佛兰卡马罗 颜色:白色 现在我需要计算每种颜色有多少辆车,然后将结果放入UITableView中。 因此,例如,在TableView中: 蓝色(2) 红色(1) 白色(1) 假设有大约70种不同的颜色 我搜索了很多关于核心数据的网站和书籍,但我仍然不知道这是否可行 可能吗?如果可能,怎么做?这些都是简单的抓取。事实上,您可以

我有一个名为Car的实体,它有2个属性名称颜色

数据库中有几辆车:

名称:本田思域

颜色:蓝色

名称:大众高尔夫

颜色:蓝色

名称:雷诺Twingo

颜色:红色

名称:雪佛兰卡马罗

颜色:白色

现在我需要计算每种颜色有多少辆车,然后将结果放入UITableView中。

因此,例如,在TableView中:

蓝色(2)

红色(1)

白色(1)

假设有大约70种不同的颜色

我搜索了很多关于核心数据的网站和书籍,但我仍然不知道这是否可行


可能吗?如果可能,怎么做?

这些都是简单的抓取。事实上,您可以使用NSFetchedResultsController,并将“color”设置为节名,它将返回所有对象的数组,并按颜色对它们进行分组

类似于

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Car"];    
NSSortDescriptor *sectionSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"color" ascending:YES];
NSSortDescriptor *nameSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sectionSortDescriptor, nameSortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];

NSFetchedResultsController *fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"color" cacheName:@"CarCache"];
fetchedResultsController.delegate = self;
self.fetchedResultsController = fetchedResultsController;

NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
    // Handle error...
}

现在,您的数据将分为多个部分,每种颜色一个部分,其中的值按名称排序。要获得数据,只需查看FRC的sections属性。

我认为前面的答案不太正确。在“获取结果”控制器中,您可以执行通常的操作,但

  • 获取实体
    Color
  • 您可以按
    名称
    (即颜色名称)排序
cellforrowatinexpath:
中,构造要显示的适当字符串

Color *color = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = [NSString stringWithFormat:@"%@ (%d)", 
   color.name, color.cars.count];
其中
cars
是从颜色到车辆的反向关系的名称