2015-05-13 38 views

回答

0

您使用NSPredicate來篩選按類別的對象,然後就可以獲取某個屬性例如只值:

NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
// Entity 
NSEntityDescription *ent = [NSEntityDescription entityForName:@"Incoming" inManagedObjectContext:context]; 
[request setEntity:ent]; 
// Predicate 
NSPredicate *pred = [NSPredicate predicateWithFormat:@"category MATCHES[cd] %@", @"FOOD"]; 
[request setPredicate:pred]; 
// Property fetch 
[request setResultType:NSDictionaryResultType]; 
[request setReturnsDistinctResults:NO]; 
[request setPropertiesToFetch:@[@"Amount"]]; 

// Execute the fetch. 
NSError *error; 
NSArray *objects = [context executeFetchRequest:request error:&error]; 
int total = 0; 
if (objects) { 
    for(NSDictionary *dict in objects) { 
     NSString *key = dict.allKeys.lastObject; 
     total += [dict[key] intValue]; 
    } 
} else { 
    NSLog(@"Fetch error: %@", error.localizedDescription); 
} 
NSLog(@"Total: %i", total); 
+0

我將如何返回到我最初稱爲這種方法?我收到的錯誤隱式轉換int到id在ARC中是不允許的 – John

+0

我不太明白,但是你可以像' - (int)getTotal;' –

+0

@pbasdf那樣定義int的返回類型,但答案確實很好。試試那個。 –

0

下面將得到一個類別和金額讀取操作:

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Incoming"]; 
fetchRequest.resultType = NSDictionaryResultType; 

NSExpression *sumExp = [NSExpression expressionWithFormat:@"sum:(amount)"]; 
NSExpressionDescription *sumED = [[NSExpressionDescription alloc] init]; 
sumED.name = @"sum"; 
sumED.expression = sumExp; 
sumED.expressionResultType = NSDoubleAttributeType; 

fetchRequest.propertiesToFetch = [@"title", sumED]; 
fetchRequest.propertiesToGroupBy = [@"title"]; 

NSArray *dictionaries = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil]; 

查看NSExpression文檔here

2

通過利用KVC(鍵值編碼),您幾乎可以免除提取請求。

首先獲取(或過濾器)與此斷言:

[NSPredicate predicateWithFormat:@"category = %@", @"Food"]; 

然後就總結得出一個結果行:

NSNumber *sum = [result valueForKeyPath:@"@sum.amount"]; 

沒有必要獲取使用NSDictionaryResultType只有某些屬性 - 只需獲取正常的NSManagedObject(核心數據將爲您優化)。