码迷,mamicode.com
首页 > 数据库 > 详细

LKDBHelper-ORM框架

时间:2015-06-03 23:35:49      阅读:740      评论:0      收藏:0      [点我收藏+]

标签:

在IOS中 存储数据的sqlite框架有FMDB,其主要的实现还是SQL 语句。而LKDBHelper是构建在该框架上的一个 ORM框架实现对象数据映射。其框架库在github上能找到。以下代码将通过LKDBHelper实现增删查改。

1 实现数据对应的Bean对象,以下提供.h文件。

#import <Foundation/Foundation.h>

@interface WBUser : NSObject

@property (nonatomic,copy) NSString *userName;

@property (nonatomic,assign) int age;

@end

2 提供实现的Dao层。

WBUserDao.h

#import <Foundation/Foundation.h>
#import "WBUser.h"

@interface WBUserDao : NSObject

+(instancetype)daoWithEntityClass:(Class)aclass;

-(void)saveUser:(WBUser *)user;

-(WBUser *)loadUserWithWherecase:(NSString *)where;

-(BOOL)updateUserWithWherecase:(NSString *)where;

-(void)deleteWithWherecase:(NSString *)where;

@end

WBUserDao.m

#import "WBUserDao.h"
#import "LKDBHelper.h"

@interface WBUserDao ()

@property (nonatomic,strong) Class entityClass;
@property (nonatomic,strong) LKDBHelper *gobalHelper;

@end

@implementation WBUserDao

+(instancetype)daoWithEntityClass:(Class)aclass
{
    WBUserDao *dao=[[[self class] alloc] initWithEntityClass:aclass];
    return dao;
}

-(instancetype)initWithEntityClass:(Class)aclass
{
    if (self=[super init]) {
        _entityClass=aclass;
        _gobalHelper=[LKDBHelper getUsingLKDBHelper];
        [_gobalHelper createTableWithModelClass:[_entityClass class]];
    }
    return self;
}

-(void)saveUser:(WBUser *)user
{
    NSLog(@"%d",[_gobalHelper insertToDB:user]);
}

-(WBUser *)loadUserWithWherecase:(NSString *)where
{
    return [_gobalHelper searchSingle:[WBUser class] where:where orderBy:nil];
}

-(BOOL)updateUserWithWherecase:(NSString *)where
{
    return [_gobalHelper updateToDB:[WBUser class] set:@"age = 15 " where:where];
}

-(void)deleteWithWherecase:(NSString *)where
{
    [_gobalHelper deleteWithClass:[WBUser class] where:where callback:^(BOOL result) {
        NSLog(@"delete result :%d",result);
    }];
}

@end

3 以下代码显示如何调用。我们在ViewDidLoad中实现

- (void)viewDidLoad {
    [super viewDidLoad];
    
    WBUser *user=[[WBUser alloc] init];
    user.userName=@"awdawda";
    user.age=18;
    
    WBUserDao *dao=[WBUserDao daoWithEntityClass:[user class]];
    [dao saveUser:user];
    
    WBUser *userData=[dao loadUserWithWherecase:@"userName='awdawda'"];
    
    BOOL updateFlag=[dao updateUserWithWherecase:@"userName='awdawda'"];
    
    WBUser *userData2=[dao loadUserWithWherecase:@"userName='awdawda'"];
    
    NSLog(@"%d  %d",updateFlag,userData2.age);
    
    [dao deleteWithWherecase:@"userName='awdawda'"];
    
}

Tip:在增删查改中,LKDBhelper实现的方式还有很多很多。具体看需求。gitHub:点击打开链接



LKDBHelper-ORM框架

标签:

原文地址:http://blog.csdn.net/qq285016127/article/details/46351771

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!