核心数据:如何显示用于在表格单元格中计算值的提取请求的结果 [英] Core data: How to display results of a fetchrequest for calculating values in a tableview cell

查看:231
本文介绍了核心数据:如何显示用于在表格单元格中计算值的提取请求的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是iOS的新手(如果我不清楚,或者问题已经在别处解决了,我先表示歉意),我经历了很多教程来学习基础知识。仍然,我一直面临以下问题与核心数据做以下:

I am relatively new to iOS (I apologize beforehand if I am not clear or if the problem has been addressed elsewhere) and I have gone through a lot of tutorials to learn the basics. Still, I have been facing issues with doing the following with core data:


  • 我理解如何从核心数据从数据提取数据,排序它并显示它,但现在我不知道如何编程性地工作一个属性(它是我的数据库中的表中的一个瞬态属性)需要计算和显示在嵌入在导航的tableview控制器中的静态tableview单元格控制器。

示例:我有一个包含两个变量整数)和inputDate(NSDate)),并且我想计算每年或每天每日输入值的平均/最小/最大

For illustration: I have a table with two variables ( InputValue (integer) and inputDate (NSDate) ) and I want to compute the average/min/max of each daily entered value per year or day. These values will be then displayed and updated each time in a tableview static cell (each computed value in a cell.)

编辑:我添加了一个一些代码来自tableview控制器这里:

I added some code from the tableview controller here:

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{

    //Configure the cell to show the user value as well as showing the date of input

    PVMesswert *wert = [self.fetchedResultsController objectAtIndexPath:indexPath];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
   [dateFormatter setDateFormat:@"dd.MM.yyyy"];
           cell.textLabel.text= [[NSString alloc] initWithFormat:@"%@ kWh", wert.inputValue];
    cell.detailTextLabel.text = [dateFormatter stringFromDate:wert.inputDate];

     }

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{    //should I have a different cell identifier for each row where I want to display a result of the calculations?
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    // Configure the cell.
    [self configureCell:cell atIndexPath:indexPath];
    return cell;
}

- (NSFetchedResultsController *)fetchedResultsController
{


     if (_fetchedResultsController != nil) {
            return _fetchedResultsController;
        }

        // Create and configure a fetch request with the PVMesswert entity.


        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"PVMessWert" inManagedObjectContext:self.managedObjectContext];
        [fetchRequest setEntity:entity];

        // Create the sort descriptors array.

        NSSortDescriptor *datumsort = [[NSSortDescriptor alloc] initWithKey:@"inputDate" ascending:NO];

        NSSortDescriptor *valueDescriptor = [[NSSortDescriptor alloc] initWithKey:@"InputValue" ascending:YES];

        NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:datumsort, /*authorDescriptor,*/ nil];
        [fetchRequest setSortDescriptors:sortDescriptors];

        // Create and initialize the fetch results controller.


        _fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"dateToString" cacheName:@"Root"];

        _fetchedResultsController.delegate = self;

        // Memory management.

        return _fetchedResultsController;
    }    

所以,在另一个tableview我有,我想显示的东西, / max / min每年的输入值(基于属性输入日期NSDat。)。应该使用NSExpression,在这种情况下,如何?

So, in another tableview I have, I want to display things like: avg/max/min Inputvalue per year (based on attribute input date NSDat.). Should I use NSExpression and in which case, how?

推荐答案

您应该使用聚合函数

您可以在一个抓取请求中检索应该相对较快的所有max / min / avg信息。

You could retrieve all the max/min/avg information in one fetch request that should be relatively fast.

聚合函数的代码应如下所示:

The code for an aggregate function should look something like this:

//Function expression generator
- (NSExpressionDescription*) aggregateFunction:(NSString*)function
                                    forKeyPath:(NSString*)keyPath
                                          name:(NSString*)name
                                    resultType:(NSAttributeType)resultType
{
    NSExpression* keyPathExpression = [NSExpression expressionForKeyPath:keyPath];
    NSExpression* funcExpression = [NSExpression expressionForFunction:function arguments:@[keyPathExpression]];
    NSExpressionDescription* expressionDescription  = [NSExpressionDescription new];
    [expressionDescription setName:name];
    [expressionDescription setExpression:funcExpression];
    [expressionDescription setExpressionResultType:resultType];
    return expressionDescription;
}

您的撷取要求应如下所示:

Your fetch request should look like this:

//someValue is an Integer64 property
//someDate is a Date property
NSFetchRequest* r = [NSFetchRequest fetchRequestWithEntityName:@"Product"];
NSExpressionDescription* minValueField = [self aggregateFunction:@"min:"
                                                      forKeyPath:@"someValue"
                                                            name:@"minValue"
                                                      resultType:NSInteger64AttributeType];
NSExpressionDescription* avgValueField = [self aggregateFunction:@"average:"
                                                      forKeyPath:@"someValue"
                                                            name:@"avgValue"
                                                      resultType:NSInteger64AttributeType];
NSExpressionDescription* maxValueField = [self aggregateFunction:@"max:"
                                                      forKeyPath:@"someValue"
                                                            name:@"maxValue"
                                                      resultType:NSInteger64AttributeType];
NSExpressionDescription* minDateField = [self aggregateFunction:@"min:"
                                                     forKeyPath:@"someDate"
                                                           name:@"minVDate"
                                                     resultType:NSDateAttributeType];
NSExpressionDescription* avgDateField = [self aggregateFunction:@"average:"
                                                      forKeyPath:@"someDate"
                                                            name:@"avgDate"
                                                      resultType:NSDateAttributeType];
NSExpressionDescription* maxDateField = [self aggregateFunction:@"max:"
                                                     forKeyPath:@"someDate"
                                                           name:@"maxDate"
                                                     resultType:NSDateAttributeType];

[r setResultType:NSDictionaryResultType];
[r setPropertiesToFetch:@[minValueField,avgValueField,maxValueField,minDateField,avgDateField,maxDateField]];

NSArray* results = [context executeFetchRequest:r error:NULL];

注意:

*信息在单个字典对象中的键与 name 参数匹配的参数创建的表达式。

*您不能使用 NSFetchedResultsController 以实时跟踪结果集中的更改,如果需要在数据库更改时进行精确计算,则需要刷新结果。

*按天分组和年,您将需要从日期字段提取日期和年份到单独的字段(例如 day year ),然后按抓取请求中的这些字段分组:

Notes:
* this will retrieve the information in a single dictionary object with keys matching the name parameter you created the expressions for.
* You cannot use a NSFetchedResultsController to track changes in the result set in 'real time' and need to refresh the results if you need calculation to be accurate as the database change.
* To group by day and year, you will need to extract the day and year from the date field into separate fields (say day and year) and then group by these fields in the fetch request:

[r setPropertiesToGroupBy:@[@"year"]];//to group by year alone

并添加 code>到要提取的属性。

and add the year to the properties to fetch.

编辑:如果您对特定年份年),您必须将年份和日期与日期分开(如前所述)。

然后只需设置一个谓词,以您需要的年份过滤:

If you are interested in a specific year (or day in year), you must separate the year and day from the date (as I mentioned before).
Then just set a predicate to filter by the year you need:

[r setPredicate:[NSPredicate predicateWithFormat:@"year = %d",someYear]];

这篇关于核心数据:如何显示用于在表格单元格中计算值的提取请求的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆