Lei's Blog

Weex邂逅FMDB

面试之家只是为了学习和交流使用Weex,题库等内容不可用于商业项目

一开始面试之家题库是在服务端,后来由于后端开发效率和界面加载时间太长等原因,所以我决定将题库移植到客户端,未来打算做成动态插入本地数据库的方式,实现数据库题目的更新。事实证明数据库移植到本地,能大大提高加载效率,比如Java科目列表有四百多道题,从读取到页面渲染完成只用了0.3秒

数据库整理

注意在将数据库打包到工程中时,读没问题,但是写偶尔会失败,所以正确的做法是在程序启动时将数据库移到沙盒中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
- (void)moveDB{
NSString * docPath = [[NSBundle mainBundle] pathForResource:@"WX" ofType:@"db"];
NSString * appDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *filePath = [appDir stringByAppendingPathComponent:@"WX.db"];
if(![fileManager fileExistsAtPath:filePath]) {
BOOL filesPresent = [self copyMissingFile:docPath toPath:appDir];
if (filesPresent) {
NSLog(@"Copy Success");
}
else
{
NSLog(@"Copy Fail");
}
}
else
{
NSLog(@"文件已存在");
}
}
- (BOOL)copyMissingFile:(NSString *)sourcePath toPath:(NSString *)toPath
{
BOOL retVal = YES; // If the file already exists, we'll return success…
NSString * finalLocation = [toPath stringByAppendingPathComponent:[sourcePath lastPathComponent]];
if (![[NSFileManager defaultManager] fileExistsAtPath:finalLocation]){
retVal = [[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:finalLocation error:NULL];
}
return retVal;
}

InterviewHome项目的原生模块中,我单独准备了一个StorageViewController来负责整理数据库,这个类里有以下两个功能

  1. 创建数据库

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    - (void)createAllSubjectTable {
    NSString *table = @"CREATE TABLE IF NOT EXISTS Subjects_Table (s_id integer PRIMARY KEY AUTOINCREMENT NOT NULL,_id varchar(128),content varchar(128),groupId varchar(128), totalNum integer, unlockTotal integer)";
    if ([_db open]) {
    BOOL sucess = [_db executeStatements:table];
    if (sucess) {
    NSLog(@"sucess %@",DB_SANDBOX_TABLE);
    } else {
    NSLog(@"faile %@",DB_SANDBOX_TABLE);
    }
    [_db close];
    }
    - (void)createAllClassTable {
    NSString *table = @"CREATE TABLE IF NOT EXISTS Class_Table (c_id integer PRIMARY KEY AUTOINCREMENT NOT NULL,s_id integer(20) NOT NULL,pageID varchar(128),showContent varchar(128),integral integer(20),title varchar(128), questcount integer(128))";
    if ([_db open]) {
    BOOL sucess = [_db executeStatements:table];
    if (sucess) {
    NSLog(@"sucess %@",DB_SANDBOX_TABLE);
    } else {
    NSLog(@"faile %@",DB_SANDBOX_TABLE);
    }
    [_db close];
    }
    }
    - (void)createQuestionsTable {
    NSString *table = @"CREATE TABLE IF NOT EXISTS Questions_Table (q_id integer PRIMARY KEY AUTOINCREMENT NOT NULL,_id varchar(128),questionTitle varchar(128),classId varchar(128),isCollection integer,answer varchar(128),author varchar(128),createTime varchar(128), number integer)";
    if ([_db open]) {
    BOOL sucess = [_db executeStatements:table];
    if (sucess) {
    NSLog(@"sucess %@",DB_SANDBOX_TABLE);
    } else {
    NSLog(@"faile %@",DB_SANDBOX_TABLE);
    }
    [_db close];
    }
    }

这里分别创建了三张表,Subjects_Table科目表、 Class_Table每个科目下有多少套题 、Questions_Table 题库表 三张表的关系是

Subjects_Table>Class_Table>Questions_Table

  1. 插入数据库

    这里有一个比较难处理的地方,因为接口一次性把所有的题目给返回了,并且是无序的,怎么把每道题根据题目所属的科目排列起来呢,这里我引入了一个字典类型的额外空间

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    - (void)insertAllQuestions:(NSArray *)questions {
    if (!questions.count) {
    return;
    }
    if ([_db open]) {
    NSInteger num = 1;
    NSMutableDictionary *recodDic = [NSMutableDictionary dictionary];
    for (NSInteger i = 0; i < questions.count; i ++) {
    @autoreleasepool {
    [_db beginTransaction];
    BOOL isRollBack = NO;
    @try {
    NSDictionary *obj = questions[i];
    NSString *_id = obj[@"_id"];
    NSString *questionTitle = obj[@"questionTitle"];
    NSString *classId = obj[@"classId"];
    NSInteger isCollection = [obj[@"isCollection"] integerValue];
    NSString *answer = obj[@"answer"];
    NSString *author = obj[@"author"];
    NSString *createTime = obj[@"createTime"];
    if (recodDic[classId]) {
    num = [recodDic[classId] integerValue];
    num++;
    } else {
    num = 1;
    }
    [recodDic setObject:@(num) forKey:classId];
    [_db executeUpdate:@"insert into Questions_Table(_id, questionTitle, classId, isCollection, answer, author, createTime, number) values (?, ?, ?, ?, ?, ?, ?, ?)", _id, questionTitle, classId, @(isCollection), answer, author, createTime, @(num)];
    } @catch (NSException *exception) {
    isRollBack = true;
    [self->_db rollback];
    } @finally {
    if (!isRollBack) {
    [self->_db commit];
    }
    }
    }
    }
    }
    }

因为数据类型中只给了 classID,并没有给 classID下的题目编号,所以在做题目详情的时候,没法读取上一题下一题,所以要在本地给每个classID下的题目创建一个序号 这里就用recodDic记录classID下的序号,如果没有classID,则新加入一个同时num为1,如果有classID就取出num+1,并重新存入字典,这样就整理出了每个classID下有多少道题,同时为每道题加入一个编号

这里题量很大,加入事物,能保证插入的效率

Weex和FMDB交互

WeexFMDB交互的方式就是通过自定义Module

  • 第一步 本地写好增删改查的语句
1
2
3
4
5
6
7
8
9
10
11
12
13
- (void)insertSubjects:(NSArray *)subjects;
- (void)insertAllQuestions:(NSArray *)questions;
- (NSArray *)seletAllSubjects;
- (NSArray *)selectQuestionsWithClassID:(NSString *)classID;
- (NSDictionary *)selectQuestionDetail:(NSString *)questionID classID:(NSString *)classID;
- (NSInteger)updateCollection:(NSString *)questionID classID:(NSString *)classID status:(NSInteger)status;
- (NSArray *)selectAllCollertion;
  • 第二步 自定义Module类

    自定义Module类,需要继承WXModuleProtocol协议,使用WX_EXPORT_METHOD将方法暴露给JavaScript调用, 使用@synthesize weexInstance可对Weex页面做一个弱引用,拿到这个页面上的信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
WX_EXPORT_METHOD(@selector(selectAllSubjects:))
WX_EXPORT_METHOD(@selector(selectQuestionsWithClassID:callBack:))
WX_EXPORT_METHOD(@selector(selectQuestionDetailWithClassID:index:callBack:))
WX_EXPORT_METHOD(@selector(updateCollectionStatus:classID:status:callBack:))
WX_EXPORT_METHOD(@selector(selectAllCollertionWithcallBack:))
- (void)selectAllSubjects:(WXKeepAliveCallback)callbak {
NSArray *array = [[WXDBManger database]seletAllSubjects];
if (callbak) {
callbak(array, false);
}
}
- (void)selectQuestionsWithClassID:(NSString *)classID callBack:(WXKeepAliveCallback)callback {
NSArray *array = [[WXDBManger database] selectQuestionsWithClassID:classID];
if (callback) {
callback(array, false);
}
}
- (void)selectQuestionDetailWithClassID:(NSString *)classID index:(NSString *)number callBack:(WXKeepAliveCallback)callback {
if (callback) {
callback([[WXDBManger database]selectQuestionDetail:number classID:classID], false);
}
}
- (void)updateCollectionStatus:(NSString *)questionID classID:(NSString *)classID status:(NSInteger)status callBack:(WXKeepAliveCallback)callback {
if (callback) {
callback([NSString stringWithFormat:@"%zi",[[WXDBManger database]updateCollection:questionID classID:classID status:status]], false);
}
}
- (void)selectAllCollertionWithcallBack:(WXKeepAliveCallback)callback {
if (callback) {
callback([[WXDBManger database]selectAllCollertion], false);
}
}
  • 第三步 将自定义Module注册到 WeexSDK

    1
    [WXSDKEngine registerModule:@"GL_DatabaseModule" withClass:NSClassFromString(@"WXDatabaseModule")];
  • 第四部 JS调用

首先定义Module变量

1
var db = weex.requireModule('GL_DatabaseModule');

然后就可以调用本地抛出的函数了, JS调用OC函数,只需写第一个参数前的方法名,多参数的话直接传参数就行,回调值用一个匿名函数来接受

1
2
3
db.selectQuestionsWithClassID(this.pageID,function(data){
self.dataArray = data;
})

这样一个完整的Module注册流程就完成了

#END

面试之家是一款用Weex写的多页面应用,目前还在与苹果审核斗争中,对Weex感兴趣的小伙们可以去关注一下,谢谢!