0x01 概述
參考:http://www.itdecent.cn/p/4a36acc32d9b
使用coredata的多嗎,好用嗎,調(diào)研才有發(fā)言權(quán),開干。
0x02 網(wǎng)上搜索概述
總體使用較少
優(yōu)點:1 不直接操作sqlte語句,容易使用。 2 和系統(tǒng)接口結(jié)合。 3 分線程主線程操作方便。
缺點:1 多個表關(guān)聯(lián)時不好操作。2數(shù)據(jù)庫升級困難。3 學(xué)習(xí)成本較高。
0x03 開始入坑
A 創(chuàng)建Data Mode

坑的地方是默認(rèn)是swift,沒有oc選項,要想使用oc要創(chuàng)建完成后手動修改,修改方法如下圖:

B 為 data mode 創(chuàng)建NSManagedObject
新建文件里面沒有那個選項了,what fack,沒了,怎么創(chuàng)建。
網(wǎng)上搜了下,隱藏在其他位置了,如下圖:

創(chuàng)建完成后,該松口氣了,然而實際他還是會讓你緊張的。
編譯報錯如下:

懵逼了吧
搜索之后發(fā)現(xiàn)是xcode的bug
https://stackoverflow.com/questions/40460307/duplicate-symbol-error-when-adding-nsmanagedobject-subclass-duplicate-link

C 保存數(shù)據(jù)
1.創(chuàng)建實體,并為實體屬性賦值
Person *p = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:context];
p.name = [NSString stringWithFormat:@"大倩倩%d",arc4random()%10];
p.age = [NSString stringWithFormat:@"%d",arc4random()%60];
2.保存數(shù)據(jù)
[context save:nil];
***************************************************************
3.查詢
建立請求
NSFetchRequest *request = [[NSFetchRequest alloc] init] ;
讀取實體
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:context];
請求連接實體
request.entity = entity;
遍歷所有實體,將每個實體的信息存放在數(shù)組中
NSArray *arr = [context executeFetchRequest:request error:nil];
for (Person *p in arr)
{
????NSLog(@"name=%@,age=%@", p.name,p.age);
}
D 讀取數(shù)據(jù)
NSFetchRequest*request = [[NSFetchRequest alloc]init];
NSEntityDescription*entity = [NSEntityDescription entityForName:@"Person"inManagedObjectContext:context];
request.entity= entity;
NSArray*arr = [context executeFetchRequest:requesterror:nil];
for(Person*pinarr) {
NSLog(@"name is: %@",p.name);
}
E 修改
//設(shè)置過濾條件
NSPredicate*predicate = [NSPredicate predicateWithFormat:@"name = %@",@"Tommy"];
request.predicate= predicate;
NSArray*arr = [context executeFetchRequest:requesterror:nil];
for(Person*pinarr) {
????p.name=@"Mini Tommy";
}
[context save:nil];
F 刪除
先查詢出符合條件的數(shù)據(jù),方法參考D讀取數(shù)據(jù)
for(Person*pinarr) {
????[context deleteObject:p];
}
[contextsave:nil];
0x04 總結(jié)
總體感覺使用比直接使用sql簡單些。
對于表的關(guān)聯(lián),數(shù)據(jù)的升級還沒試驗。