[英]How to specify Destination for Core Data fetchRequest programmatically?
[英]Core data: How to display results of a fetchrequest for calculating values in a tableview cell
我對iOS相對較新(如果不清楚或如果問題已在其他地方解決,我會事先道歉),並且我通過了大量的教程來學習基礎知識。 盡管如此,我在處理核心數據時仍然遇到問題:
舉例說明:我有一個包含兩個變量的表(InputValue(整數)和inputDate(NSDate)),我想計算每年或每天每個每日輸入值的平均值/最小值/最大值 。 然后,每次在tableview靜態單元格中顯示和更新這些值(單元格中每個計算值)。
編輯:我在這里從tableview控制器添加了一些代碼:
- (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;
}
因此,在另一個表格視圖中,我想顯示如下內容:每年平均/最大/最小輸入值(基於屬性輸入日期NSDat。)。 我應該使用NSExpression,在這種情況下如何使用?
您應將聚合函數用於此類計算。
您可以在一個相對較快的提取請求中檢索所有最大/最小/平均信息。
聚合函數的代碼應如下所示:
//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;
}
您的提取請求應如下所示:
//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
),然后在提取請求中按以下字段進行分組:
[r setPropertiesToGroupBy:@[@"year"]];//to group by year alone
並將year
添加到要獲取的屬性中。
編輯:如果您對特定的年份(或年份中的某天)感興趣,則必須將年份和日期與日期分開(如我之前提到的)。
然后只需設置一個謂詞即可按您需要的年份進行過濾:
[r setPredicate:[NSPredicate predicateWithFormat:@"year = %d",someYear]];
有兩種主要方法:
一世。 使用NSFetchedResultsController
在cellForRowAtIndexPath
手動執行
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell =
[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// get your managed object
NSManagedObject *managedObject = [_fetchedResultsController objectAtIndexPath:indexPath];
// do any computations
float value1 = [[managedObject valueForKey:@"value1"] floatValue];
float value2 = [[managedObject valueForKey:@"value2"] floatValue];
float average = (value1+value2)/2;
// display average in cell
cell.textLabel.text = [NSString stringWithFormat:@"Average: %f", average];
return cell;
}
ii。 另一種方法是使用諸如Sensible TableView之類的Core Data框架。 這些框架除了自動管理在自定義單元格中顯示此類計算之外,還自動獲取您的數據並顯示它們。 使用Core Data可以節省大量時間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.