我有一個表視圖是由分段開關排序。我想通過NSNumericSearch對錶格進行排序,以便得到1,2,11,22而不是1,11,2,22。我正在使用核心數據。fetchedresultscontroller行爲
如果我創建了多個記錄'color'屬性保持不變(即所有'紅色'),同時改變長度,最初排序的長度是正確的(1,2,11,22)。如果我切換到分段控件的另一個selectedSegmentIndex,例如'形狀'或'長度',我會在相同的數據上得到錯誤的排序順序(1,11,2,22)。
我以爲fetchedResultsController應該重新計算數據,並調用tableView來重新載入數據。
我沒有使用謂詞。我已經嘗試將緩存名稱設置爲零,但不起作用。我也嘗試過deleteCacheWithName:雖然它可能需要位於不同的位置。
一些代碼:
- (NSFetchedResultsController *)fetchedResultsController{
if (__fetchedResultsController != nil) {
return __fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyEntity" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20];
switch (segmentedControl.selectedSegmentIndex) {
case 0:
sortKey = @"color";
break;
case 1:
sortKey = @"length";
break;
case 2:
sortKey = @"smell";
break;
case 3:
sortKey = @"shape";
break;
default:
sortKey = @"color";
break;
}
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortKey ascending:YES comparator:^(id obj1, id obj2) { return [obj1 compare:obj2 options:NSNumericSearch]; }];
NSSortDescriptor *sortDescriptor2 = [NSSortDescriptor sortDescriptorWithKey:@"length" ascending:YES comparator:^(id obj1, id obj2) { return [obj1 compare:obj2 options:NSNumericSearch]; }];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor,sortDescriptor2, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:sortKey cacheName:@"Master"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
abort();
}
return __fetchedResultsController;
}
- (IBAction)changeSegment:(id)sender {
switch (segmentedControl.selectedSegmentIndex) {
case 0:
sortKey = @"color";
break;
case 1:
sortKey = @"length";
break;
case 2:
sortKey = @"smell";
break;
case 3:
sortKey = @"shape";
break;
default:
sortKey = @"one";
break;
}
self.fetchedResultsController = nil;
[self.tableView reloadData];
//[NSFetchedResultsController deleteCacheWithName:@"Master"];
}
誰能幫助我在第一次正確的,第二次不正確排序的這種行爲?