0
이름이 FoodItem
인 엔터티가 있고 price
(double) 속성이 있습니다. 이상적으로이 코드의 출력은 다음과 같습니다.모든 NSManagedObjects 특성의 평균을 계산하십시오.
Average Price is: 6.00
값 6.00에 액세스하는 방법은 확실하지 않지만, 누구든지 나를 도울 수 있습니까? 이에 대한 가져 오기 결과 컨트롤러를 사용하는 이유 이해가 안
NSEntityDescription *entity = [NSEntityDescription entityForName:@"FoodItem" inManagedObjectContext:self.managedObjectContext];
NSManagedObject *o1 = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:self.managedObjectContext];
[o1 setValue:@(5.00) forKey:@"price"];
NSManagedObject *o2 = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:self.managedObjectContext];
[o2 setValue:@(7.00) forKey:@"price"];
[self.managedObjectContext save:nil];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
[request setSortDescriptors:@[]];
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"price"];
NSExpression *averagePriceExpression = [NSExpression expressionForFunction:@"average:"
arguments:@[keyPathExpression]];
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
[expressionDescription setName:@"averagePrice"];
[expressionDescription setExpression:averagePriceExpression];
[expressionDescription setExpressionResultType:NSDecimalAttributeType];
[request setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]];
NSFetchedResultsController *controller = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Master"];
[controller performFetch:nil];
NSLog(@"Average price is: %@", @"");
NSFetchedResultsController를 사용해야하는 유일한 실시간 데이터는 데이터가 UITableView에 표시되는 경우입니다. – Skyler
예. 'UICollectionView' (테이블과 유사)와 함께 사용할 수도 있습니다. –
이것은 어리석은 질문처럼 들릴지 모르겠지만, 내가 전에 가져온 것과 같은 속성의 평균은 여전히 가져 와서 NSArray * 객체에 저장되는 관리 객체입니까? 어떻게 접근 할 수 있습니까? – Skyler