首页 > 代码库 > 为数据表对象(NSManagedObject)添加排序

为数据表对象(NSManagedObject)添加排序

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.dataSourceobjectAtIndex:sourceIndexPath.row];

    sourceMeditation.order =[NSStringstringWithFormat:@"%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.dataSourceobjectAtIndex:i];

            m.order =[NSStringstringWithFormat:@"%i",[m.attribute6integerValue]-1];

            [sourceMeditation.managedObjectContextsave:nil];

        }

        

    }else

    {

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

        {

            Meditation *m = [self.dataSourceobjectAtIndex:i];

            m.order =[NSStringstringWithFormat:@"%i",[m.attribute6integerValue]+1];

            [sourceMeditation.managedObjectContextsave: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.dataSourceobjectAtIndex:i];

            m.order =[NSStringstringWithFormat:@"%i",[m.attribute6integerValue]-1];

            [appDelegate saveContext];

        }


}

为数据表对象(NSManagedObject)添加排序