我想查询我的实体“DIncome”来总结属性“信用”但我只想要其“daystamp”属性等于今天的整体。下面的代码让我很接近,但我不明白如何完成这段代码,以便将信用 DIncome 属性的总和输出到我的视图控制器上的标签。
这是我得到的;
//Get today date
NSDate *dateSelect = [NSDate date];
//formate today date as day only "dd"
NSDateFormatter *dfdd = [[NSDateFormatter alloc]init];
[dfdd setDateFormat:@"dd"];
NSString *formattedDatedd = [dfdd stringFromDate:dateSelect];
//Fetchrequest
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"DIncome" inManagedObjectContext:context];
[request setEntity:entity];
// Specify that the request should return dictionaries.
[request setResultType:NSDictionaryResultType];
// Create an expression for the key path.
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"credit"];
NSExpression *sumExpression = [NSExpression expressionForFunction:@"sum:" arguments:[NSArray arrayWithObject:keyPathExpression]];
// Create an expression description using the minExpression and returning a date.
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
// The name is the key that will be used in the dictionary for the return value.
[expressionDescription setName:@"sumCredit"];
[expressionDescription setExpression:sumExpression];
[expressionDescription setExpressionResultType:NSDateAttributeType];
// Set the request's properties to fetch just the property represented by the expressions.
[request setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]];
// Execute the fetch.
NSError *error = nil;
NSArray *objects = [context executeFetchRequest:request error:&error];
if (objects == nil) {
// Handle the error.
}
else {
if ([objects count] > 0) {
NSLog(@"Credit Sum: %@", [[objects objectAtIndex:0] valueForKey:@"sumCredit"]);
self.dayDisplayLabel.text = sumExpression;
}
}
对于问题的第二部分,我需要将信用总和设置为我的 dayDisplayLabel 这不起作用,因为它是一个不兼容的指针,将 NSString 分配给 NSExpression
self.dayDisplayLabel.text = sumExpression;
我怎样才能做到这一点?