我想按周和日期對核心數據條目進行分組。我有一個名爲WorkEntry
的核心數據實體,其中的屬性是weekBegin
和date
。在這些我保存它保存的日期以及與該日期相對應的一週的第一天。我使用weekBegin
作爲部分名稱,我希望單元格顯示沒有重複條目的日期。我用http://felipecypriano.com/2011/09/21/core-data-how-to-do-a-select-distinct/作爲指導。這裏是我的代碼:嘗試按日期對核心數據提取結果進行分組
獲取請求與returnsDistinctResults
:
- (NSFetchRequest *)workDayFetchRequest {
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"WorkEntry"];
CoreDataStack *coreDataStack = [CoreDataStack defaultStack];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"WorkEntry" inManagedObjectContext:coreDataStack.managedObjectContext];
fetchRequest.entity = entity;
fetchRequest.propertiesToFetch = [NSArray arrayWithObject:[[entity propertiesByName] objectForKey:@"weekBegin"]];
fetchRequest.returnsDistinctResults = YES;
fetchRequest.resultType = NSDictionaryResultType;
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"weekBegin" ascending:YES];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
NSError *error = nil;
self.distinctResults = [coreDataStack.managedObjectContext executeFetchRequest:fetchRequest error:&error];
return fetchRequest;
}
這給了我一個數組稱爲distinctResults
這是我在使用:
CellForRowAtIndexPath
:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
cell.textLabel.text = [self.distinctResults objectAtIndex:indexPath.row];
return cell;
}
但是我有一種感覺那可能不對。當我切換到表格視圖中的應用程序崩潰與此異常:
-[NSKnownKeysDictionary1 length]: unrecognized selector sent to instance 0x8c7c8a0
我會任何幫助你們能給真的很感激。試圖弄清楚這一點我一直在瘋狂。由於
您的提取請求告訴Core Data將每個結果作爲NSDictionary返回。很可能某個地方你試圖訪問一個結果,就好像它是一個NSString,當它是一個NSDictionary的時候 - 可能讀取一個屬性值(也就是說你假設它返回了一些屬性作爲結果的每一項) - 可能'weekBegin'。 – quellish 2014-08-31 01:03:01