如何使用Core Data在UITableView中维护显示顺序?

Ton*_*old 11 sorting iphone core-data uitableview

我在使用UITableView时让我的Core Data实体玩得很好并且订购时遇到了一些麻烦.

我在StackOverflow上经历了一些教程和其他问题,但似乎没有一个明确或优雅的方法来做到这一点 - 我真的希望我错过了一些东西.

我有一个Core Data实体,它上面有一个名为"displayOrder"的int16属性.我使用已经在"displayOrder"上排序的NSFetchRequest来返回我的UITableView的数据.除了重新排序之外的一切都得到了尊重.这是我的(低效)moveRowAtIndePath方法:

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {         

    NSUInteger fromIndex = fromIndexPath.row;  
    NSUInteger toIndex = toIndexPath.row;

    FFObject *affectedObject = [self.fetchedResultsController.fetchedObjects objectAtIndex:fromIndex];  
    affectedObject.displayOrderValue = toIndex;

    [self FF_fetchResults];


    for (NSUInteger i = 0; i < [self.fetchedResultsController.fetchedObjects count]; i++) {  
        FFObject *otherObject = [self.fetchedResultsController.fetchedObjects objectAtIndex:i];  
        NSLog(@"Updated %@ / %@ from %i to %i", otherObject.name, otherObject.state, otherObject.displayOrderValue, i);  
        otherObject.displayOrderValue = i;  
    }

    [self FF_fetchResults];  
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以向我指出一些示例代码的方向,或者看看我做错了什么?tableview显示更新OK,我可以通过我的日志消息看到displayOrder属性正在更新.它不是一直保存和重新加载,并且对于这个实现感觉非常"偏离"(除了我所有FFObjects的浪费迭代).

提前感谢您提出的任何建议.

ger*_*ry3 27

我看了你的代码,这可能会更好:

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {         

    NSUInteger fromIndex = fromIndexPath.row;  
    NSUInteger toIndex = toIndexPath.row;

    if (fromIndex == toIndex) {
        return;
    }

    FFObject *affectedObject = [self.fetchedResultsController.fetchedObjects objectAtIndex:fromIndex];  
    affectedObject.displayOrderValue = toIndex;

    NSUInteger start, end;
    int delta;

    if (fromIndex < toIndex) {
        // move was down, need to shift up
        delta = -1;
        start = fromIndex + 1;
        end = toIndex;
    } else { // fromIndex > toIndex
        // move was up, need to shift down
        delta = 1;
        start = toIndex;
        end = fromIndex - 1;
    }

    for (NSUInteger i = start; i <= end; i++) {
        FFObject *otherObject = [self.fetchedResultsController.fetchedObjects objectAtIndex:i];  
        NSLog(@"Updated %@ / %@ from %i to %i", otherObject.name, otherObject.state, otherObject.displayOrderValue, otherObject.displayOrderValue + delta);  
        otherObject.displayOrderValue += delta;
    }

    [self FF_fetchResults];  
}
Run Code Online (Sandbox Code Playgroud)

  • 这应与http://stackoverflow.com/questions/1077568/how-to-implement-re-ordering-of-coredata-records/2013070#2013070并行实施 (5认同)