2013-03-12 3 views
1

У меня есть стол со 100 рядами. Один из столбцов имеет столбец с именем «MeetingType», который всегда является значением int (1, 2 или 3).Количество основных данных (или отдельных)

Как создать предикат выборки, который вернет счетчик a из числа строк другого типа ?

Например, если из 100 строк 50 имели тип = 0 и 25 имели тип = 1, а остальные 25 имели тип = 2. набор результатов будет иметь значение 3. (показывая, что во всех строках было 3 разных типа)

ответ

1

выборка результатов в виде набора, затем подсчет количества элементов в наборе.

Редактировать # 2: Существует также следующая ссылка, которая поможет вам получить более сжатый способ сделать это. http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/KeyValueCoding/Articles/CollectionOperators.html#//apple_ref/doc/uid/20002176-BAJEAIEE

Редактировать: хорошо, вот попытка.

//you will be working on some sort of entity, i've guessed its called Meeting 
NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Meeting" inManagedObjectContext:managedObjectContext]; 
[request setEntity:entity]; 

//you can set a predicate here if you like, eg only meetings with a certain name or something 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name = %@", type_name]; 
[request setPredicate:predicate]; 
// Specify that the request should return dictionaries. 
[request setResultType:NSDictionaryResultType]; 

// Create an expression for the key path, in this case MeetingType 
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"MeetingType"]; 


// Create an expression description using the maxExpression 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:@"meetingTypes"]; 
[expressionDescription setExpression:keyPathExpression]; 
[expressionDescription setExpressionResultType:NSInteger32AttributeType]; 

// 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 = [sharedAISDataService.managedObjectContext executeFetchRequest:request error:&error];  

//check for no error 
if(error == nil){ 
    //the following set will contain unique NSNumber objects 
    NSSet *setOfMeetinTypes = [NSSet setWithArray:objects]; 

    int numberOfMeetinTypes = [setOfMeetinTypes count]; 
    //you now have the number of unique meeting types 

} 
+0

Не могли бы вы показать мне пример. Я так новичок в основных данных и особенно предикатов, что мне все еще не удается создать их с нуля. Еще раз спасибо. – jdross

+0

ooh, я не смогу его синтаксически исправлять с верхней части головы, но я должен быть в состоянии дать вам достаточно, чтобы идти по правильному пути. – Bergasms

1

Альтернативой подсчету в наборе можно выполнить три подсчета.

NSError *error; 
int count; 
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:NSStringFromClass([yourObject class])]; 
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"MeetingType == 1"]; 
count = [managedObjectContext countForFetchRequest:fetchRequest error:&error]; 

if (count > 0) { 
    //Add 1 to your set or handle appropriately 
} 

fetchRequest.predicate = [NSPredicate predicateWithFormat:@"MeetingType == 2"]; 
count = [managedObjectContext countForFetchRequest:fetchRequest error:&error]; 
if (count > 0) { 
    //Add 2 to your set or handle appropriately 
} 

fetchRequest.predicate = [NSPredicate predicateWithFormat:@"MeetingType == 3"]; 
count = [managedObjectContext countForFetchRequest:fetchRequest error:&error]; 
if (count > 0) { 
    //Add 3 to your set or handle appropriately 
} 

Это должно быть намного быстрее, чем на самом деле тянет объекты, и искать в этом наборе для тех, с различными атрибутами MeetingType.

4

Вот простой и чистый NSFetchRequest версия:

NSFetchRequest* request = [NSFetchRequest fetchRequestWithEntityName:@"Meeting"]; 
    [request setResultType:NSDictionaryResultType]; 
    [request setPropertiesToGroupBy:@[@"MeetingType"]]; 
    [request setPropertiesToFetch:@[@"MeetingType"]]; 
    NSError* error = nil; 
    NSUInteger count = [[context executeFetchRequest:request error:&error] count]; 
Смежные вопросы