自定义排序


#import "BaseViewController.h"


@interface SortTableCellVC : BaseViewController


@property (nonatomic, copy) NSString *domainId;


@property (nonatomic,copy) void (^changeSortCellBlock)(NSString *domainId);


@end






#import "SortTableCellVC.h"

#import "SortItemCell.h"

#import "SortHeaderView.h"

#import "DBSortManager.h"


@interface SortTableCellVC () <UICollectionViewDelegate, UICollectionViewDataSource>


@property (nonatomic, strong) UICollectionView *sortCollectionView;

@property (nonatomic, strong) SortItemCell *dragingItem;        //拖拽时覆盖的Item

@property (nonatomic, strong) NSIndexPath *dragingIndexPath;    //正在拖拽的indexpath

@property (nonatomic, strong) NSIndexPath *targetIndexPath;     //目标位置的indexpath


@property (nonatomic, strong) NSMutableArray *inUseItemArray;   //已选数据源

@property (nonatomic, strong) NSMutableArray *unUseItemArray;   //未选数据源

@property (nonatomic, strong) NSMutableArray *unPowerItemArray; //无权限数据源


@property (nonatomic, assign) CGFloat columnNumber;     // collectionView 行item个数

@property (nonatomic, assign) CGFloat sortItemWith;     // collectionView item with

@property (nonatomic, assign) CGFloat sortItemHeight;   // collectionView item height

@property (nonatomic, assign) CGFloat sortSpace;        // collectionView 每一行item之间的间距

@property (nonatomic, assign) CGFloat sortLineSpace;    // collectionView 行间距


@end


static NSString *sortItemCellID = @"SortItemCellID";

static NSString *sortHeaderViewID = @"SortHeaderViewID";


@implementation SortTableCellVC


#pragma mark - Life Cycle


- (void)viewDidLoad {

    [super viewDidLoad];

    

    [self initialization];

    [self setupUI];

}


- (void)initialization

{

    _columnNumber = 3;

    _sortItemWith = 50;

    _sortItemHeight = _sortItemWith + 20;

    _sortSpace = (SCREENWIDTH - _sortItemWith*_columnNumber)/(_columnNumber + 1);

    _sortLineSpace = 20;

    

    _inUseItemArray = [NSMutableArray array];

    _unUseItemArray = [NSMutableArray array];

    _unPowerItemArray = [[NSMutableArray alloc] init];

    

    _dragingIndexPath = [[NSIndexPath alloc] init];

    _targetIndexPath = [[NSIndexPath alloc] init];

 

    

    NSArray *models = [[DBSortManager sharedManager] fetchAllData];

    for (int i = 0; i < models.count; i++) {

        DBSortModel *model = models[i];

        if ([model.sortName isEqualToString:@"111"]){

            model.imageName = @"111";

            model.title = @"111";

        }

        /** 发电完成率 */

        if ([model.sortName isEqualToString:@"222"]){

            model.imageName = @"222";

            model.title = @"222";

        }

        /** 电站PR */

        if ([model.sortName isEqualToString:@"333"]){

            model.imageName = @"333";

            model.title = @"333";

        }

        /** 运维统计 */

        if ([model.sortName isEqualToString:@"444"]){

            model.imageName = @"444";

            model.title = @"444";

        }

        /** 节能减排 */

        if ([model.sortName isEqualToString:@"555"]){

            model.imageName = @"555";

            model.title = @"555";

        }


        if ([model.isShow isEqualToString:@"1"]) {

            [_inUseItemArray addObject:model];

        } else if ([model.isShow isEqualToString:@"2"]) {

            [_unUseItemArray addObject:model];

        } else {

            [_unPowerItemArray addObject:model];

        }

    }

}


- (void)backHomeReloadView

{

    //重置数据库

    [[DBSortManager sharedManager] deleteAllData];

    for (int i = 0; i < _inUseItemArray.count; i++) {

        DBSortModel *model = _inUseItemArray[i];

        model.sortID = i + 1;

        model.isShow = @"1";

        [[DBSortManager sharedManager] addSortModel:model];

    }

    for (int i = 0; i < _unUseItemArray.count; i++) {

        DBSortModel *model = _unUseItemArray[i];

        model.sortID = _inUseItemArray.count + i + 1;

        model.isShow = @"2";

        [[DBSortManager sharedManager] addSortModel:model];

    }

    for (int i = 0; i < _unPowerItemArray.count; i++) {

        DBSortModel *model = _unPowerItemArray[i];

        model.sortID = _inUseItemArray.count + _unUseItemArray.count + i + 1;

        model.isShow = @"3";

        [[DBSortManager sharedManager] addSortModel:model];

    }


    

    [self dismissViewControllerAnimated:YES completion:^{

        //返回刷新界面

        self.changeSortCellBlock(_domainId);

    }];

}


#pragma mark - UI


- (void)setupUI

{

    //背景视图

    UIImageView *bgImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"add_view_bg"]];

    bgImgView.frame = self.view.bounds;

    [self.view addSubview:bgImgView];

    

    CGFloat backBtnTopHeight = 50 + kBottomaDaptationHeight;

    //底部返回按钮

    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];

    backBtn.frame = CGRectMake(0, self.view.ftn_height - backBtnTopHeight, 40, 40);

    backBtn.ftn_centerX = self.view.ftn_centerX;

    [backBtn setImage:[UIImage imageNamed:@"add_backbtn_bg"] forState:UIControlStateNormal];

    [backBtn addTarget:self action:@selector(backHomeReloadView) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:backBtn];

    

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];

    flowLayout.itemSize = CGSizeMake(_sortItemWith,_sortItemHeight); //item大小

    flowLayout.sectionInset = UIEdgeInsetsMake(_sortLineSpace, _sortSpace, _sortLineSpace, _sortSpace); //(上 左 下 右) 边距

    flowLayout.minimumLineSpacing = _sortLineSpace; // 行最小间距

    flowLayout.minimumInteritemSpacing = _sortSpace; // 行item之间最小间距

    flowLayout.headerReferenceSize = CGSizeMake(SCREENWIDTH, 40); //section头部大小

    

    _sortCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, kNavBarHeight - 20, SCREENWIDTH, SCREENHEIGHT - backBtnTopHeight - (kNavBarHeight - 20)) collectionViewLayout:flowLayout];

    _sortCollectionView.showsHorizontalScrollIndicator = NO;

    _sortCollectionView.backgroundColor = [UIColor clearColor];

    [_sortCollectionView registerClass:[SortItemCell class] forCellWithReuseIdentifier:sortItemCellID];

    [_sortCollectionView registerClass:[SortHeaderView class]

        forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:sortHeaderViewID];

    _sortCollectionView.delegate = self;

    _sortCollectionView.dataSource = self;

    [self.view addSubview:_sortCollectionView];

    

    //添加长按手势

    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressMethod:)];

    longPress.minimumPressDuration = 0.3f;

    [_sortCollectionView addGestureRecognizer:longPress];

    

    //拖拽时移动的item

    _dragingItem = [[SortItemCell alloc] initWithFrame:CGRectMake(0, 0, _sortItemWith, _sortItemHeight)];

    _dragingItem.isMoving = YES;

    [_sortCollectionView addSubview:_dragingItem];

}


#pragma mark -

#pragma mark LongPressMethod


- (void)longPressMethod:(UILongPressGestureRecognizer *)gesture

{

    CGPoint point = [gesture locationInView:_sortCollectionView];

    switch (gesture.state) {

        case UIGestureRecognizerStateBegan:

            [self dragBegin:point];

            break;

        case UIGestureRecognizerStateChanged:

            [self dragChanged:point];

            break;

        case UIGestureRecognizerStateEnded:

            [self dragEnd];

            break;

        default:

            break;

    }

}


//拖拽开始 找到被拖拽的item

- (void)dragBegin:(CGPoint)point

{

    _dragingIndexPath = [self getDragingIndexPathWithPoint:point];

    if (!_dragingIndexPath) {return;}

    NSLog(@"拖拽开始");

    [_sortCollectionView bringSubviewToFront:_dragingItem];

    SortItemCell *item = (SortItemCell *)[_sortCollectionView cellForItemAtIndexPath:_dragingIndexPath];

    item.isMoving = YES;

    //更新被拖拽的item

    _dragingItem.isMoving = NO;

    _dragingItem.frame = item.frame;

    [_dragingItem setSortItemCellInfo:_inUseItemArray[_dragingIndexPath.row] section:0];

    [_dragingItem setTransform:CGAffineTransformMakeScale(1.1, 1.1)];

}


//正在被拖拽

-(void)dragChanged:(CGPoint)point

{

    if (!_dragingIndexPath) {return;}

    //NSLog(@"拖拽中。。。");

    _dragingItem.center = point;

    _targetIndexPath = [self getTargetIndexPathWithPoint:point];

    //交换位置 如果没有找到_targetIndexPath则不交换位置

    if (_dragingIndexPath && _targetIndexPath) {

        //更新数据源

        [self rearrangeInUseInfo];

        //更新item位置

        [_sortCollectionView moveItemAtIndexPath:_dragingIndexPath toIndexPath:_targetIndexPath];

        _dragingIndexPath = _targetIndexPath;

    }

}


//拖拽结束

-(void)dragEnd

{

    if (!_dragingIndexPath) {return;}

    NSLog(@"拖拽结束");

    CGRect endFrame = [_sortCollectionView cellForItemAtIndexPath:_dragingIndexPath].frame;

    [_dragingItem setTransform:CGAffineTransformMakeScale(1.0, 1.0)];

    [UIView animateWithDuration:0.3 animations:^{

        _dragingItem.frame = endFrame;

    } completion:^(BOOL finished) {

        _dragingItem.isMoving = YES;

        SortItemCell *item = (SortItemCell *)[_sortCollectionView cellForItemAtIndexPath:_dragingIndexPath];

        item.isMoving = NO;

    }];

}


#pragma mark -

#pragma mark 辅助方法


//获取被拖动IndexPath的方法

-(NSIndexPath*)getDragingIndexPathWithPoint:(CGPoint)point{

    NSIndexPath* dragIndexPath = nil;

    //最后剩一个不可以排序

    if ([_sortCollectionView numberOfItemsInSection:0] == 1) {return dragIndexPath;}

    for (NSIndexPath *indexPath in _sortCollectionView.indexPathsForVisibleItems) {

        //下半部分不需要排序

        if (indexPath.section > 0) {continue;}

        //在上半部分中找出相对应的Item

        if (CGRectContainsPoint([_sortCollectionView cellForItemAtIndexPath:indexPath].frame, point)) {

            dragIndexPath = indexPath;

            if (indexPath.row != 0) {

                //设置不可以排序

            }

            break;

        }

    }

    return dragIndexPath;

}


//获取目标IndexPath的方法

-(NSIndexPath*)getTargetIndexPathWithPoint:(CGPoint)point{

    NSIndexPath *targetIndexPath = nil;

    for (NSIndexPath *indexPath in _sortCollectionView.indexPathsForVisibleItems) {

        //如果是自己不需要排序

        if ([indexPath isEqual:_dragingIndexPath]) {continue;}

        //第二组不需要排序

        if (indexPath.section > 0) {continue;}

        //在第一组中找出将被替换位置的Item

        if (CGRectContainsPoint([_sortCollectionView cellForItemAtIndexPath:indexPath].frame, point)) {

            targetIndexPath = indexPath;

            if (indexPath.row != 0) {

                

            }

        }

    }

    return targetIndexPath;

}


#pragma mark -

#pragma mark - CollectionView Delegate & DataSource


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView

{

    return 2;

}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section

{

    return section == 0 ? _inUseItemArray.count : _unUseItemArray.count;

}


- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath

{

    SortHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:sortHeaderViewID forIndexPath:indexPath];

    if (indexPath.section == 0) {

        headerView.title = @"已选择内容";

        headerView.subTitle = @"点击可以移除,长按拖动进行显示排序";

        headerView.imageName = @"add_show_header";

    } else {

        headerView.title = @"自定义界面显示内容";

        headerView.subTitle = @"点击图标添加";

        headerView.imageName = @"add_hide_header";

    }

    return headerView;

}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

{

    SortItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:sortItemCellID forIndexPath:indexPath];

    WS(weakSelf);

    cell.clickDeleteImgViewBlock = ^{

        [weakSelf collectionView:collectionView didSelectItemAtIndexPath:indexPath];

    };

    if (indexPath.section == 0) {

        [cell setSortItemCellInfo:_inUseItemArray[indexPath.row] section:0];

    } else {

        [cell setSortItemCellInfo:_unUseItemArray[indexPath.row] section:1];

    }

    return cell;

}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

{

    NSLog(@"点击item");

    

    NSIndexPath *toIndexPath;

    if (indexPath.section == 0) {

        id obj = [_inUseItemArray objectAtIndex:indexPath.row];

        [_inUseItemArray removeObject:obj];

        [_unUseItemArray insertObject:obj atIndex:0];

        toIndexPath = [NSIndexPath indexPathForRow:0 inSection:1];

        

    } else {

        id obj = [_unUseItemArray objectAtIndex:indexPath.row];

        [_unUseItemArray removeObject:obj];

        [_inUseItemArray addObject:obj];

        toIndexPath = [NSIndexPath indexPathForRow:_inUseItemArray.count - 1 inSection:0];

        

    }

    

    [_sortCollectionView performBatchUpdates:^{

        [_sortCollectionView moveItemAtIndexPath:indexPath toIndexPath:toIndexPath];

    } completion:^(BOOL finished) {

        [_sortCollectionView reloadItemsAtIndexPaths:@[toIndexPath]];

    }];

}


#pragma mark -

#pragma mark 刷新方法


//拖拽排序后需要重新排序数据源

-(void)rearrangeInUseInfo

{

    id obj = [_inUseItemArray objectAtIndex:_dragingIndexPath.row];

    [_inUseItemArray removeObject:obj];

    [_inUseItemArray insertObject:obj atIndex:_targetIndexPath.row];

}


@end


#import <UIKit/UIKit.h>

#import "DBSortModel.h"

@interface SortItemCell : UICollectionViewCell


@property (nonatomic, strong) UIImageView *deleteImgView;


//是否正在移动状态

@property (nonatomic, assign) BOOL isMoving;


- (void)setSortItemCellInfo:(DBSortModel *)model section:(NSInteger)section;


@property (nonatomic,copy) void (^clickDeleteImgViewBlock)();


@end


#import "SortItemCell.h"


@interface SortItemCell ()


@property (nonatomic, strong) UILabel *titleLabel;


@property (nonatomic, strong) UIImageView *imageView;


@property (nonatomic, strong) CAShapeLayer *borderLayer;


@end


@implementation SortItemCell


- (id)initWithFrame:(CGRect)frame

{

    self = [super initWithFrame:frame];

    if (self) {

        

        [self initialization];

        [self setupMainView];

    }

    return self;

}


- (void)initialization

{

    self.userInteractionEnabled = YES;

}


- (void)setupMainView

{

    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.ftn_width, self.ftn_width)];

    imageView.userInteractionEnabled = YES;

    [self.contentView addSubview:imageView];

    _imageView = imageView;

    

    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_imageView.frame), self.ftn_width, 20)];

    titleLabel.font = [UIFont systemFontOfSize:12];

    titleLabel.textColor = [UIColor whiteColor];

    titleLabel.textAlignment = NSTextAlignmentCenter;

    titleLabel.userInteractionEnabled = YES;

    [self.contentView addSubview:titleLabel];

    _titleLabel = titleLabel;

    

    CGFloat deleteImgViewWidth = 12;

    CGFloat deleteImgViewX = self.ftn_width/2 + 0.7*self.ftn_width/2;

    CGFloat deleteImgViewY = self.ftn_width/2 - 0.7*self.ftn_width/2 - deleteImgViewWidth;

    UIImageView *deleteImgView = [[UIImageView alloc] initWithFrame:CGRectMake(deleteImgViewX, deleteImgViewY, deleteImgViewWidth, deleteImgViewWidth)];

    deleteImgView.image = [UIImage imageNamed:@"add_delete_select"];

    [self.contentView addSubview:deleteImgView];

    _deleteImgView = deleteImgView;

    

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickDeleteImgView)];

    [deleteImgView addGestureRecognizer:tap];

}


- (void)clickDeleteImgView

{

    if (self.clickDeleteImgViewBlock) {

        self.clickDeleteImgViewBlock();

    }

}


- (void)layoutSubviews

{

    [super layoutSubviews];

    _imageView.frame = CGRectMake(0, 0, self.ftn_width, self.ftn_width);

    _titleLabel.frame = CGRectMake(0, CGRectGetMaxY(_imageView.frame), self.ftn_width, 20);

}


- (void)setIsMoving:(BOOL)isMoving

{

    _isMoving = isMoving;

    if (_isMoving) {

        self.hidden = YES;

        _deleteImgView.hidden = YES;

    } else {

        self.hidden = NO;

        _deleteImgView.hidden = NO;

    }

}


- (void)setSortItemCellInfo:(DBSortModel *)model section:(NSInteger)section

{

    _imageView.image = [UIImage imageNamed:model.imageName];

    _titleLabel.text = model.title;

    if (section == 0) {

        _deleteImgView.hidden = NO;

    } else {

        _deleteImgView.hidden = YES;

    }

}


@end


#import <UIKit/UIKit.h>


@interface SortHeaderView : UICollectionReusableView


@property (copy,nonatomic) NSString *title;


@property (copy,nonatomic) NSString *subTitle;


@property (copy,nonatomic) NSString *imageName;


@end


#import "SortHeaderView.h"


@interface SortHeaderView ()

{

    UILabel *_titleLabel;

    

    UILabel *_subtitleLabel;

    

    UIImageView *_imgView;

}

@end


@implementation SortHeaderView


- (instancetype)initWithFrame:(CGRect)frame

{

    if (self = [super initWithFrame:frame]) {

        [self initialization];

        [self setupMainView];

    }

    return self;

}


- (void)initialization

{

    self.backgroundColor = [UIColor clearColor];

}


- (void)setupMainView

{

    _imgView = [[UIImageView alloc] init];

    _imgView.frame = CGRectMake(10, 0, 30, 20);

    _imgView.contentMode = UIViewContentModeCenter;

    [self addSubview:_imgView];

    

    _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_imgView.frame) + 10, 0, 250, self.ftn_height/2)];

    _titleLabel.font = [UIFont systemFontOfSize:14];

    _titleLabel.textColor = [UIColor whiteColor];

    [self addSubview:_titleLabel];

    

    _imgView.ftn_centerY = _titleLabel.ftn_centerY;

    

    _subtitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(_titleLabel.frame), CGRectGetMaxY(_titleLabel.frame), 250, self.ftn_height/2)];

    _subtitleLabel.font = [UIFont systemFontOfSize:14];

    _subtitleLabel.textColor = [UIColor whiteColor];

    [self addSubview:_subtitleLabel];

}


- (void)setTitle:(NSString *)title

{

    _title = title;

    _titleLabel.text = title;

}


- (void)setSubTitle:(NSString *)subTitle

{

    _subTitle = subTitle;

    _subtitleLabel.text = subTitle;

}


- (void)setImageName:(NSString *)imageName

{

    _imageName = imageName;

    _imgView.image = [UIImage imageNamed:imageName];

}


@end






#import <Foundation/Foundation.h>

#import "DBSortModel.h"


@interface DBSortManager : NSObject


// 单例

+ (instancetype)sharedManager;


// 检查是否存在数据

- (BOOL)isExsitsWithSortID:(NSInteger)sortID;


// 添加数据

- (BOOL)addSortModel:(DBSortModel *)model;


// 删除数据

- (BOOL)deleteWithSortID:(NSInteger)sortID;


// 更新数据

- (BOOL)updateSortModel:(DBSortModel *)model;


// 查询数据

- (NSArray *)selectModelWithSortID:(NSInteger)sortID;


// 获取所有的记录

- (NSArray *)fetchAllData;


// 删除所有数据

- (void)deleteAllData;


@end



#import "DBSortManager.h"

#import "FMDB.h"


#define TABLENAME @"Sorts"

#define ID @"sortID"

#define SORTNAME @"sortName"

#define ISSHOW @"isShow"


@implementation DBSortManager

{

    FMDatabase *_database; // FMDB数据库管理对象

}


// 创建单例对象

+ (instancetype)sharedManager

{

    static dispatch_once_t token;

    static DBSortManager * gDBManager = nil;


    dispatch_once(&token, ^{

        if (!gDBManager) {

            gDBManager = [[DBSortManager alloc] init];

        }

    });

    return gDBManager;

}


- (instancetype)init

{

    if (self = [super init]) {

        NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];

        NSString *dbPath = [documentPath stringByAppendingPathComponent:@"sort.sqlite"];

        NSLog(@"dbPath == %@",dbPath);

        

        // 创建FMDatabase

        // 如果在目录下没有这个数据库文件,将创建该文件。

        _database = [[FMDatabase alloc] initWithPath:dbPath];


        // 创建数据库表,表中的字段

        //其中IF NOT EXISTS:如果表不存在则建立;ID integer PRIMARY KEY AUTOINCREMENT:表示ID为integer类型的自动累加的主键;sortName text not null:表示name是不能为空的字段;

        if ([_database open]) {

            NSLog(@"打开数据库成功");

            NSString * createSql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS '%@' ('%@' integer PRIMARY KEY AUTOINCREMENT, '%@' text NOT NULL, '%@' text NOT NULL)",TABLENAME, ID, SORTNAME, ISSHOW];

            // 当数据库文件创建完成时,首先创建数据表,如果没有这个表,就去创建,有了就不创建

            BOOL result = [_database executeUpdate:createSql];

            if (result) {

                NSLog(@"建表成功");

            } else {

                NSLog(@"建表失败");

            }

            [_database close];

        } else {

            NSLog(@"打开数据库失败");

        }

    }

    return self;

}


#pragma mark - 增删改查


// 检查是否存在数据

- (BOOL)isExsitsWithSortID:(NSInteger)sortID

{

    [_database open];

    //SQL 使用单引号来环绕文本值(大部分数据库系统也接受双引号)。如果是数值,不使用引号  这里用引号查不到数据

    NSString *selectSql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@ = %ld", TABLENAME, ID, sortID];

    FMResultSet *set = [_database executeQuery:selectSql];

    // 判断是否已存在数据

    if ([set next]) {

        NSLog(@"存在此条数据");

        [_database close];

        return YES;

    } else {

        NSLog(@"不存在此条数据");

        [_database close];

        return NO;

    }

}


// 添加数据

- (BOOL)addSortModel:(DBSortModel *)model

{

    // 删除老数据

    [self deleteWithSortID:model.sortID];

    

    [_database open];

    // 添加新数据

    NSString *insertSql = [NSString stringWithFormat:@"INSERT INTO '%@' ('%@', '%@', '%@') VALUES (%ld, '%@', '%@')", TABLENAME, ID, SORTNAME, ISSHOW, model.sortID, model.sortName, model.isShow];

    BOOL res = [_database executeUpdate:insertSql];

    if (res) {

        NSLog(@"添加成功");

    } else {

        NSLog(@"添加失败%@",_database.lastErrorMessage);

    }

    [_database close];

    return res;

}


// 删除数据

- (BOOL)deleteWithSortID:(NSInteger)sortID

{

    /*

     不拼接NSString字符串,直接写语句

     必须注意:此种方式只有变量值可以用?来替代,别的(如表名,键名都必须直接写在前面不能用格式化的方法来操作)

     传给executeQuery()的参数必须是NSObject,不能是原始数据类型,否则报EXC_BAD_ACCESS

     */

    

    // 判断将要删除的应用记录是否存在

    BOOL isExists = [self isExsitsWithSortID:sortID];

    

    [_database open];

    if (isExists) {

        NSString *deleteSql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@ = %ld", TABLENAME, ID, sortID];

        BOOL res = [_database executeUpdate:deleteSql];

        if (res) {

            NSLog(@"删除成功");

            [_database close];

            return YES;

        } else {

            NSLog(@"删除失败%@",_database.lastErrorMessage);

        }

    } else {

        NSLog(@"该记录不存在");

    }

    [_database close];

    return NO;

}


// 更新数据

- (BOOL)updateSortModel:(DBSortModel *)model

{

    BOOL isExsits = [self isExsitsWithSortID:model.sortID];

    [_database open];

    if (isExsits) {

        NSString *updateSql = [NSString stringWithFormat:@"UPDATE %@ SET %@ = %@ WHERE %@ = %ld", TABLENAME, ISSHOW, model.isShow, ID, model.sortID];

        BOOL res = [_database executeUpdate:updateSql];

        if (res) {

            NSLog(@"更新成功");

            [_database close];

            return YES;

        } else {

            NSLog(@"更新失败:%@",_database.lastErrorMessage);

        }

    } else {

        NSLog(@"该记录不存在");

    }

    [_database close];

    return NO;

}


// 查询数据

- (NSArray *)selectModelWithSortID:(NSInteger)sortID

{

    NSMutableArray *array = [[NSMutableArray alloc] init];

    if ([_database open]) {  // 查询操作使用executeQuery,并涉及到了FMResultSet

        // 按照ID号降序排列,如果只有order by默认是升序的 等同于ASC      DESC降序

        //        NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ ORDER BY %@",TABLENAME,ID];

        //        FMResultSet * set = [_database executeQuery:sql];

        

        NSString *selectSql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@ = %ld", TABLENAME, ID, sortID];

        FMResultSet *set = [_database executeQuery:selectSql];

        while ([set next]) {

            DBSortModel * model = [[DBSortModel alloc] init];

            model.sortID = [set intForColumn:ID];

            model.sortName = [set stringForColumn:SORTNAME];

            model.isShow = [set stringForColumn:ISSHOW];

            [array addObject:model];

        }

        [_database close];

    } else {

        NSLog(@"打开数据库失败");

    }

    return array;

}


// 获取所有的记录

- (NSArray *)fetchAllData

{

    [_database open];

    // 找出表中所有的数据

    NSString *fetchSql = [NSString stringWithFormat:@"SELECT * FROM %@", TABLENAME];

    FMResultSet *set = [_database executeQuery:fetchSql];

    

    // 循环遍历取出数据

    NSMutableArray *array = [[NSMutableArray alloc] init];

    while ([set next]) {

        DBSortModel * model = [[DBSortModel alloc] init];

        // 从结果集中获取数据

        // 注:sqlite数据库不区别分大小写

        model.sortID = [set intForColumn:ID];

        model.sortName = [set stringForColumn:SORTNAME];

        model.isShow = [set stringForColumn:ISSHOW];

        [array addObject:model];

    }

    [_database close];

    return array;

}


// 删除所有数据

- (void)deleteAllData

{

    [_database open];

    NSString *deleteSql = [NSString stringWithFormat:@"DELETE FROM %@", TABLENAME];

    BOOL isDeleteAll = [_database executeUpdate:deleteSql];

    if (isDeleteAll) {

        NSLog(@"删除所有数据成功");

    } else {

        NSLog(@"删除所有数据失败");

    }

    [_database close];

}


// 删除表

- (void)dropTable

{

    if ([_database open]) {

        NSString *sqlDrop = [NSString stringWithFormat:@"DROP TABLE %@",TABLENAME];

        BOOL res =  [_database executeUpdate:sqlDrop];

        if (res) {

            NSLog(@"Drop table success");

        } else {

            NSLog(@"Drop table Failure");

        }

        [_database close];

    } else {

        NSLog(@"打开数据库失败");

    }

}


@end



#import <Foundation/Foundation.h>


@interface DBSortModel : NSObject


@property (nonatomic, assign) NSInteger sortID;

@property (nonatomic, copy) NSString *sortName;

@property (nonatomic, copy) NSString *title;

@property (nonatomic, copy) NSString *imageName;

@property (nonatomic, copy) NSString *isShow;


@end


#import "DBSortModel.h"


@implementation DBSortModel


@end




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值