原理很簡單嘱兼,參考 這里.赵辕,先用coredata把數(shù)據(jù)保存下來盆顾,運行程序后把保存的數(shù)據(jù)copy出來放到predata文件夾锥惋,然后寫好將predata文件夾中的3個數(shù)據(jù)庫文件copy到原coredata的代碼,就完成數(shù)據(jù)的預置了褂删。
下面是一個完整的demo
#import "ViewController.h"
#import <CoreData/CoreData.h>
#import "DataClass.h"
@interface ViewController ()
@property (nonatomic, strong)UITextField *textF;
@property (nonatomic, strong)UIButton *saveBtn;
@property (nonatomic,strong)NSManagedObjectContext *context;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self setPreData];
[self.view addSubview:self.textF];
[self.view addSubview:self.saveBtn];
//創(chuàng)建持久化存儲協(xié)調器(助手)
//注意: Model的擴展名--> momd(xcoredatamodeld自動變成成momd結尾的文件)
NSURL *modelURL = [[NSBundle mainBundle]URLForResource:@"predata_test" withExtension:@"momd"];
NSManagedObjectModel *objectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
NSPersistentStoreCoordinator *storeCoordinator = [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:objectModel];
//創(chuàng)建持久化存儲對象(特殊)
//URL: 告訴持久化存儲對象, 當前的數(shù)據(jù)庫放的位置(沙盒/Documents/Model.sqlite)
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
NSString *sqlitePath = [docPath stringByAppendingPathComponent:@"predata_test.sqlite"];
NSURL *sqliteURL = [NSURL fileURLWithPath:sqlitePath];
NSError *error = nil;
NSPersistentStore *persistentStore = [storeCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:sqliteURL options:nil error:&error];
//將持久化存儲協(xié)調器對象和上下文綁定
[self.context setPersistentStoreCoordinator:storeCoordinator];
[self loadData];
}
- (NSManagedObjectContext *)context {
if (!_context) {
_context = [[NSManagedObjectContext alloc] init];
}
return _context;
}
- (UITextField *)textF{
if (!_textF) {
_textF = [[UITextField alloc]initWithFrame:CGRectMake(100, 100, 100, 20)];
_textF.backgroundColor = [UIColor blueColor];
}
return _textF;
}
- (UIButton *)saveBtn{
if (!_saveBtn) {
_saveBtn = [[UIButton alloc]initWithFrame:CGRectMake(220, 100, 50, 20)];
_saveBtn.backgroundColor = [UIColor yellowColor];
[_saveBtn addTarget:self action:@selector(saveText) forControlEvents:UIControlEventTouchUpInside];
}
return _saveBtn;
}
- (void)saveText{
DataClass *data = [NSEntityDescription insertNewObjectForEntityForName:@"DataClass" inManagedObjectContext:self.context];
data.contentOfTextF = self.textF.text;
NSError *error = nil;
[self.context save:&error];
if (error) {
NSLog(@"插入失敗: %@", error.userInfo);
} else {
NSLog(@"插入成功");
}
}
- (void)loadData{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"DataClass"];
NSError *error = nil;
NSArray *resultArray = [self.context executeFetchRequest:request error:&error];
DataClass *data = [resultArray firstObject];
self.textF.text = data.contentOfTextF;
}
- (void)setPreData{
NSString *sqldbPath = [NSString stringWithFormat:@"%@/predata_test.sqlite", [[NSBundle mainBundle] bundlePath]];
NSLog(@"%@",sqldbPath);
NSString *sqlshmPath = [NSString stringWithFormat:@"%@/predata_test.sqlite-shm", [[NSBundle mainBundle] bundlePath]];
NSString *sqlwalPath = [NSString stringWithFormat:@"%@/predata_test.sqlite-wal", [[NSBundle mainBundle] bundlePath]];
NSError *error = nil;
NSFileManager *fmanager = [NSFileManager defaultManager];
[fmanager copyItemAtPath:sqldbPath toPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/predata_test.sqlite"] error:&error];
if (error) {
NSLog(@"Move db failed,%@",error.userInfo);
error = nil;
}
[fmanager copyItemAtPath:sqlshmPath toPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/predata_test.sqlite-shm"] error:&error];
if (error) {
NSLog(@"Move db shm failed,%@",error.userInfo);
error = nil;
}
[fmanager copyItemAtPath:sqlwalPath toPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/predata_test.sqlite-wal"] error:&error];
if (error) {
NSLog(@"Move db wal failed ,%@",error.userInfo);
error = nil;
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
SQLite的WAL機制
由于coredata實際上是 iOS中提供了對原始SQLite數(shù)據(jù)庫API訪問的封裝飞醉,所以生成的數(shù)據(jù)庫文件有3個如圖:
數(shù)據(jù)文件
1.什么是WAL?
WAL的全稱是Write Ahead Logging屯阀,它是很多數(shù)據(jù)庫中用于實現(xiàn)原子事務的一種機制缅帘,SQLite在3.7.0版本引入了該特性。
2.WAL如何工作难衰?
在引入WAL機制之前钦无,SQLite使用rollback journal機制實現(xiàn)原子事務。
rollback journal機制的原理是:在修改數(shù)據(jù)庫文件中的數(shù)據(jù)之前盖袭,先將修改所在分頁中的數(shù)據(jù)備份在另外一個地方失暂,然后才將修改寫入到數(shù)據(jù)庫文件中;如果事務失敗鳄虱,則將備份數(shù)據(jù)拷貝回來弟塞,撤銷修改;如果事務成功拙已,則刪除備份數(shù)據(jù)决记,提交修改。
WAL機制的原理是:修改并不直接寫入到數(shù)據(jù)庫文件中倍踪,而是寫入到另外一個稱為WAL的文件中系宫;如果事務失敗,WAL中的記錄會被忽略建车,撤銷修改扩借;如果事務成功,它將在隨后的某個時間被寫回到數(shù)據(jù)庫文件中癞志,提交修改往枷。
同步WAL文件和數(shù)據(jù)庫文件的行為被稱為checkpoint(檢查點)框产,它由SQLite自動執(zhí)行凄杯,默認是在WAL文件積累到1000頁修改的時候;當然秉宿,在適當?shù)臅r候戒突,也可以手動執(zhí)行checkpoint,SQLite提供了相關的接口描睦。執(zhí)行checkpoint之后膊存,WAL文件會被清空。
在讀的時候,SQLite將在WAL文件中搜索隔崎,找到最后一個寫入點今艺,記住它,并忽略在此之后的寫入點(這保證了讀寫和讀讀可以并行執(zhí)行)爵卒;隨后虚缎,它確定所要讀的數(shù)據(jù)所在頁是否在WAL文件中,如果在钓株,則讀WAL文件中的數(shù)據(jù)实牡,如果不在,則直接讀數(shù)據(jù)庫文件中的數(shù)據(jù)轴合。
在寫的時候创坞,SQLite將之寫入到WAL文件中即可,但是必須保證獨占寫入受葛,因此寫寫之間不能并行執(zhí)行题涨。
WAL在實現(xiàn)的過程中,使用了共享內存技術总滩,因此携栋,所有的讀寫進程必須在同一個機器上,否則咳秉,無法保證數(shù)據(jù)一致性婉支。
3.WAL的優(yōu)點與缺點
優(yōu)點:
1.讀和寫可以完全地并發(fā)執(zhí)行,不會互相阻塞(但是寫之間仍然不能并發(fā))澜建。
2.WAL在大多數(shù)情況下向挖,擁有更好的性能(因為無需每次寫入時都要寫兩個文件)。
3.磁盤I/O行為更容易被預測炕舵。
缺點:
1.訪問數(shù)據(jù)庫的所有程序必須在同一主機上何之,且支持共享內存技術。
2.每個數(shù)據(jù)庫現(xiàn)在對應3個文件:<yourdb>.db咽筋,<yourdb>-wal(日志文件)溶推,<yourdb>-shm(日志索引文件)。
3.當寫入數(shù)據(jù)達到GB級的時候奸攻,數(shù)據(jù)庫性能將下降蒜危。
4.WAL引入的兼容性問題
在啟用了WAL之后,數(shù)據(jù)庫文件格式的版本號由1升級到了2睹耐,因此辐赞,3.7.0之前的SQLite無法識別啟用了WAL機制的數(shù)據(jù)庫文件。
禁用WAL會使數(shù)據(jù)庫文件格式的版本號恢復到1硝训,從而可以被SQLite 3.7.0之前的版本識別响委。
5.WAL引入的性能問題
在一般情況下新思,WAL會提高SQLite的事務性能;但是在某些極端情況下赘风,卻會導致SQLite事務性能的下降夹囚。
1.在事務執(zhí)行時間較長或者要修改的數(shù)據(jù)量達到GB級的時候,WAL文件會被占用邀窃,它會暫時阻止checkpoint的執(zhí)行(checkpoint會清空WAL文件)崔兴,這將導致WAL文件變得很大,增加尋址時間蛔翅,最終導致讀寫性能的下降敲茄。
2.當checkpoint執(zhí)行的時候,會降低當時的讀寫性能山析,因此堰燎,WAL可能會導致周期的性能下降。