ios - 对 UItableView 中的单元格重新排序并将(新顺序)插入数据库

标签 ios uitableview sdk insert

我有一个由 NSMutableArray 填充的表。用户可以按照自己的意愿对单元格(行)进行重新排序。我想将记录从继承重新排序序列的数组插入数据库。

所以说表已加载: 第 1 行 第 2 行 第 3 行 第 4 行

用户重新排序为: 第 4 行 第 2 行 第 1 行 第 3 行

我想将数据按照重新排序的顺序推送到数据库。但是,当我通过 UITableView 对行重新排序后通过循环插入所有四行时,该顺序将以原始顺序(而不是重新排列的顺序)进入数据库。

有没有办法从重新排序的表中刷新数组?

最佳答案

您的记录应该有一个“订单”字段并将其存储到数据库中。从数据库加载时,您应该使用字段对记录进行排序。

编辑:下面的代码说明了这个想法

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
    if (destinationIndexPath.row > sourceIndexPath.row) {
        for (NSInteger row = sourceIndexPath.row + 1; row <= destinationIndexPath.row; ++row) {
            Record* record = array[row];
            record.row = [NSNumber numberWithInt:record.row.intValue - 1];
        }
    } else if (destinationIndexPath.row < sourceIndexPath.row) {
        for (NSInteger row = destinationIndexPath.row; row < sourceIndexPath.row; ++row) {
            Record* record = array[row];
            record.row = [NSNumber numberWithInt:record.row.intValue + 1];
        }
    }
    Record* record = array[sourceIndexPath.row];
    record.row = [NSNumber numberWithInt:destinationIndexPath.row];
    [array removeObjectAtIndex:sourceIndexPath.row];
    [array insertObject:record atIndex:destinationIndexPath.row];
    [self save];
}

- (void)loadFromCoreData {
    NSFetchRequest* request = [[NSFetchRequest alloc] init];
    NSEntityDescription* entity = [NSEntityDescription entityForName:@"Record" inManagedObjectContext:_managedObjectContext];
    request.entity = entity;

    NSSortDescriptor* sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"row" ascending:YES];
    NSArray* sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    request.sortDescriptors = sortDescriptors;

    NSError* error;
    array = [[_managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
}

关于ios - 对 UItableView 中的单元格重新排序并将(新顺序)插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21568814/

相关文章:

Android studio 更新 SDK 卡住

ios - 如何在 iPhone 设置显示中显示不可编辑的文本

iphone - 后台 iOS 应用程序是否会收到显示屏即将进入休眠状态的通知?

ios - 为什么 UITableViewCell 保持高亮?

iphone - 将应用程序无线部署到 iPhone?

java - 如何在JComboBox中显示SDK列表?

ios - UIScreen 主边界不考虑实际设备屏幕尺寸

ios - 保存UITableView的用户输入数据

iOS UITableView 单元格缩进

ios - 如何从一个 xib 文件中注册多个 TableViewCells?