最近在研究iOS的數(shù)據(jù)存取,就簡單的總結一下。
CoreData
1.是什么
Core Data是iOS5之后才出現(xiàn)的一個框架爹脾,它提供了對象-關系映射(ORM)的功能,即能夠將OC對象轉化成數(shù)據(jù)找田,保存在SQLite數(shù)據(jù)庫文件中,也能夠將保存在數(shù)據(jù)庫中的數(shù)據(jù)還原成OC對象着憨。
2.有什么用
簡單的說就是能將OC的對象和數(shù)據(jù)相互轉化墩衙,利用Core Data框架,可以輕松地將數(shù)據(jù)庫里面的2條記錄轉換成2個OC對象,也可以輕松地將2個OC對象保存到數(shù)據(jù)庫中漆改,變成2條表記錄心铃,而且不用寫一條SQL語句。
3.怎么用
新建一個實體Entity挫剑,命名為Student去扣,添加兩個屬性。
新建實體Teacher樊破,一個屬性name愉棱。建立和Student實體的關系(Inverse填Student后,Student的Inverse屬性也會自動補上)哲戚。
下面就是見證奇跡的時刻了奔滑,創(chuàng)建NSManagedObject,即利用Core Data取出的實體都是NSManagedObject類型的惫恼,能夠利用鍵-值對來存取數(shù)據(jù)。
你會發(fā)現(xiàn)Teacher和Student類都自動創(chuàng)建了澳盐,現(xiàn)在就能隨意使用了祈纯。
那么問題來了,這樣就完了嗎叼耙?
當然沒有腕窥!說到數(shù)據(jù)庫和數(shù)據(jù)存取就離不開,增筛婉、刪簇爆、改、查爽撒。
搭建上下文環(huán)境
當然這一步一般都在AppDelegate里搭建好了入蛆,如果夠懶得話,就直接調用硕勿。
AppDelegate*app = [UIApplicationsharedApplication].delegate;
NSManagedObjectContext*context = app.managedObjectContext;
這種方式創(chuàng)建的sqlite數(shù)據(jù)庫名 默認為 工程名.sqlite 但有要求的話哨毁,也可自行修改。
增
Student *p =[NSEntityDescription insertNewObjectForEntityForName:
@"Student"inManagedObjectContext:context];
p.name=@"李四";
p.no=@11;
Teacher *teacher = [NSEntityDescription insertNewObjectForEntityForName:
@"Teacher"inManagedObjectContext:context];
teacher.name=@"李老師";
p.teacher = teacher;?
//保存設置 把內(nèi)存中的數(shù)據(jù)同步到數(shù)據(jù)庫文件當中
[app saveContext];
刪
NSFetchRequest*request = [[NSFetchRequest alloc]initWithEntityName:@"Student"];
NSArray*persons = [context executeFetchRequest:request error:nil];
for(Person*p in persons) {
[context deleteObject:p];
[app saveContext];
}
改
NSFetchRequest*request = [[NSFetchRequest alloc]initWithEntityName:@"Student"];
NSArray*persons = [context executeFetchRequest:request error:nil];
for(Person*p in persons) {
?if([p.name isEqualToString:@"李四"])
? {
? ? p.name=@"王五";
? ? [app saveContext];
? }
}
查
//創(chuàng)建查詢請求
NSFetchRequest* request = [[NSFetchRequest alloc]initWithEntityName:@"Student"];
NSArray*persons = [context executeFetchRequest:request error:nil];
for(Person *p in persons) {
NSLog(@"%@ %@",p.name,p.no);
NSLog(@" %@",p.teacher.name);
}
Tips
寫完感覺有點亂源武,記錄的較零碎扼褪,研究的也較淺,繼續(xù)學習粱栖!