步骤

将原版db等数据文件以资源文件形式加入到工程目录中。
判断 NSCachesDirectory 目录是否已有该文件,木有则从 mainBundle 资源包拷贝一份过去。
用 NSFileManager、SQLiteManager 等对相应文件进行读/写操作。

栗子

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
44
45
46
47
//NSCachesDirectory
#define kCAPathDir @"/DB"
#define kCAPathCollegeDB @"/DB/college.db"
//mainBundle
#define kMBPathCollegeDB @"/college.db"
//member var
NWSQLiteManager *_collegesDBMgr;
//init
//NOTICE : DIR"NSCachesDirectory"
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDir = [paths objectAtIndex:0];
NSFileManager *file_mgr = [NSFileManager defaultManager];
[file_mgr createDirectoryAtPath:[cachesDir stringByAppendingString:kCAPathDir] withIntermediateDirectories:YES attributes:nil error:nil];//create dir.
NSString *file_path = [cachesDir stringByAppendingString:kCAPathCollegeDB];
if(![file_mgr fileExistsAtPath:file_path]) {
//DLog(@"file is not exist");
NSString *dataPath = [[[NSBundle mainBundle]bundlePath]stringByAppendingString:kMBPathCollegeDB];
NSError *error;
if([file_mgr copyItemAtPath:dataPath toPath:file_path error:&error]) {
//DLog(@"copy file success");
} else {
//DLog(@"%@",error);
}
}
_collegesDBMgr = [[NWSQLiteManager alloc]initWithDatabaseNamed:file_path];
//update database records.
//NOTICE : "replace into"
NSString *sql = [NSString stringWithFormat:@"replace into `ex_colleges` (`id`, `college_name`, `CITY_CODE`, `PROVINCE_CODE`, `modifiedTime`) values(%d, '%@', '%@', '%@', '%@');",
item.collegeid.intValue,
item.college_name,
item.city_code,
item.province_code,
item.modified_time
];
[_collegesDBMgr getRowsForQuery:sql];

小结

使用了目录 NSCachesDirectory
使用了sqlite特有语句 replace into
Enjoy the code :D