一个数据表对象(NSManagedObject)加入排序

本文介绍如何在Swift中使用UITableView实现数据项拖拽排序功能,并在删除数据项时更新排序字段,确保数据顺序正确无误。

eg:数据库表对象


@interface Meditation : NSManagedObject

@property (nonatomic, retain) NSString * order;//用来排序的属性值。用0、1、2、3...排序

@end


//在这种方法里操作

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath

{

    Meditation *sourceMeditation=[self.dataSource objectAtIndex:sourceIndexPath.row];

    sourceMeditation.order =[NSString stringWithFormat:@"%i",destinationIndexPath.row];

    [sourceMeditation.managedObjectContext save:nil];

//两种情况一种是上移,第二种是下移

1.sourceIndexPath.row>destinationIndexPath.row

2.sourceIndexPath.row>destinationIndexPath.row


    if (sourceIndexPath.row < destinationIndexPath.row)

    {

        for (NSInteger i = sourceIndexPath.row+1; i <= destinationIndexPath.row; i ++)

        {

            Meditation *m = [self.dataSource objectAtIndex:i];

            m.order =[NSString stringWithFormat:@"%i",[m.attribute6 integerValue]-1];

            [sourceMeditation.managedObjectContext save:nil];

        }

        

    }else

    {

        for (NSInteger i = sourceIndexPath.row-1; i >= destinationIndexPath.row; i--)

        {

            Meditation *m = [self.dataSource objectAtIndex:i];

            m.order =[NSString stringWithFormat:@"%i",[m.attribute6 integerValue]+1];

            [sourceMeditation.managedObjectContext save:nil];

        }

    }


}

//当对象被删除的时候(依照order的升序排列)。把删除数据以下的数据对象的order属性值-1

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{

    if (editingStyle == UITableViewCellEditingStyleDelete) {

        for (int i=indexPath.row; i<self.dataSource.count; i++) {

            Meditation *m = [self.dataSource objectAtIndex:i];

            m.order =[NSString stringWithFormat:@"%i",[m.attribute6 integerValue]-1];

            [appDelegate saveContext];

        }


}

版权声明:本文博客原创文章,博客,未经同意,不得转载。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值