2013-04-09 29 views
0

我希望NSFetchRequest爲我的UITableViewController根據特定的屬性對相似的記錄(實體)進行分組。我目前分兩步進行,但我相信有可能會使用+ (NSExpression *)expressionForAggregate:(NSArray *)collection使用NSExpression組合實體並返回一個NSArray或NSArray元素

有人可以幫助使用適當的代碼嗎?

下面是返回一個數組的數組,我的兩個步驟的代碼:

+(NSArray *)getTopQforDogByProgram2:(Dog *)dog 
        inProgram:(RunProgramTypes)programType 
       inManagedContext:(NSManagedObjectContext *)context { 
    NSString *searchString; 

    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Run"]; 
    request.predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"dog.callName = '%@'",dog.callName]]; 
    NSSortDescriptor *classSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"runClass" ascending:NO]; 
    request.sortDescriptors = [NSArray arrayWithObject:classSortDescriptor]; 

    NSError *error = nil; 
    NSArray *dataArray = [context executeFetchRequest:request error:&error]; 

    NSMutableArray *returnArray = [[NSMutableArray alloc] init]; 
    if ([dataArray count] > 0) { 
     NSMutableArray *pointArray = [[NSMutableArray alloc] init]; 
     for (Run *run in dataArray) { 
      if (! [returnArray count]) { 
       [pointArray addObject:run]; 
       [returnArray addObject:pointArray]; 
      } else { 
       BOOL wasSame = FALSE; 
       for (NSMutableArray *cmpArray in returnArray) { 
        Run *cmpRun = [cmpArray lastObject]; 
        if (cmpRun.runClass == run.runClass) { 
         [cmpArray addObject:run]; 
         wasSame = TRUE; 
         break; 
        } 
       } 
       if (! wasSame) { 
        pointArray = [[NSMutableArray alloc] init]; 
        [pointArray addObject:run]; 
        [returnArray addObject:pointArray]; 

       } 
      } 
     } 
    } 
    return returnArray; 
} 

回答

0

你可以使用一個獲取結果控制器做切片你是這樣的:

NSFetchedResultsController* controller = [[NSFetchedResultsController alloc] initWithFetchRequest:request 
                     managedObjectContext:context 
                      sectionNameKeyPath:@"runClass" 
                        cacheName:nil]; 
NSMutableArray* sections = [[NSMutableArray alloc] initWithCapacity:[controller sections] count]; 
for (id<NSFetchedResultsSectionInfo> section in [controller sections]) { 
    NSMutableArray* sectionCopy = [NSMutableArray arrayWithArray:[section objects]]; 
    [sections addObject:sectionCopy]; 
} 

或者自己做:(給定的結果按runClass排序)

NSMutableArray* sections = [NSMutableArray new]; 
NSMutableArray* currentSection = [NSMutableArray new]; 
for (Run* run in dataArray) { 
    Run* lastObject = (Run*)[currentSection lastObject]; 
    if (lastObject && (run.runClass == lastObject.runClass)) { 
     currentSection = [NSMutableArray new]; 
     [sections addObject:currentSection]; 
    } 
    [currentSection addObject:run]; 
}