我要娶你做我的CoreData探入!

一、CoreData的簡(jiǎn)單使用

準(zhǔn)備工作

  • 創(chuàng)建數(shù)據(jù)庫(kù)

    1. 新建文件琢蛤,選擇CoreData -> DataModel
    2. 添加實(shí)體(表)蜓堕,Add Entity
    3. 給表中添加屬性,點(diǎn)擊Attributes下方的‘+’號(hào)
  • 創(chuàng)建模型文件

    1. 新建文件博其,選擇CoreData -> NSManaged Object subclass
    2. 根據(jù)提示套才,選擇實(shí)體
  • 通過(guò)代碼,關(guān)聯(lián)數(shù)據(jù)庫(kù)和實(shí)體

    - (void)viewDidLoad {
        [super viewDidLoad];
    
        /*
         * 關(guān)聯(lián)的時(shí)候慕淡,如果本地沒(méi)有數(shù)據(jù)庫(kù)文件背伴,Coreadata自己會(huì)創(chuàng)建
         */
        
        // 1. 上下文
        NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
        
        // 2. 上下文關(guān)連數(shù)據(jù)庫(kù)
    
        // 2.1 model模型文件
        NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
        
        // 2.2 持久化存儲(chǔ)調(diào)度器
        // 持久化,把數(shù)據(jù)保存到一個(gè)文件峰髓,而不是內(nèi)存
        NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
        
        // 2.3 設(shè)置CoreData數(shù)據(jù)庫(kù)的名字和路徑
        NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *sqlitePath = [doc stringByAppendingPathComponent:@"company.sqlite"];
    
        [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:nil];
        
        context.persistentStoreCoordinator = store;
        _context = context;
    
    }
    

CoreData的基本操作(CURD)

  • 添加元素 - Create

    -(IBAction)addEmployee{
    
        // 創(chuàng)建一個(gè)員工對(duì)象 
        //Employee *emp = [[Employee alloc] init]; 不能用此方法創(chuàng)建
        Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context];
        emp.name = @"wangwu";
        emp.height = @1.80;
        emp.birthday = [NSDate date];
        
        // 直接保存數(shù)據(jù)庫(kù)
        NSError *error = nil;
        [_context save:&error];
        
        if (error) {
            NSLog(@"%@",error);
        }
    }     
    
  • 讀取數(shù)據(jù) - Read

    -(IBAction)readEmployee{
        
        // 1.FetchRequest 獲取請(qǐng)求對(duì)象
        NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
        
        // 2.設(shè)置過(guò)濾條件
        // 查找zhangsan
        NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",
                            @"zhangsan"];
        request.predicate = pre;
        
        // 3.設(shè)置排序
        // 身高的升序排序
        NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO];
        request.sortDescriptors = @[heigtSort];
        
        // 4.執(zhí)行請(qǐng)求
        NSError *error = nil;
        
        NSArray *emps = [_context executeFetchRequest:request error:&error];
        if (error) {
            NSLog(@"error");
        }
        
        //NSLog(@"%@",emps);
        //遍歷員工
        for (Employee *emp in emps) {
            NSLog(@"名字 %@ 身高 %@ 生日 %@",emp.name,emp.height,emp.birthday);
        }
    }
    
  • 修改數(shù)據(jù) - Update

    -(IBAction)updateEmployee{
        // 改變zhangsan的身高為2m
        
        // 1.查找到zhangsan
        // 1.1FectchRequest 抓取請(qǐng)求對(duì)象
        NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
        
        // 1.2設(shè)置過(guò)濾條件
        // 查找zhangsan
        NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@", @"zhangsan"];
        request.predicate = pre;
    
        // 1.3執(zhí)行請(qǐng)求
        NSArray *emps = [_context executeFetchRequest:request error:nil];
         
        // 2.更新身高
        for (Employee *e in emps) {
            e.height = @2.0;
        }
        
        // 3.保存
        NSError *error = nil;
        [_context save:&error];
        
        if (error) {
            NSLog(@"%@",error);
        }
    }
    
  • 刪除數(shù)據(jù) - Delete

    -(IBAction)deleteEmployee{
        
        // 刪除 lisi
        
        // 1.查找lisi
        // 1.1FectchRequest 抓取請(qǐng)求對(duì)象
        NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
        
        // 1.2設(shè)置過(guò)濾條件
        // 查找zhangsan
        NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",
                            @"lisi"];
        request.predicate = pre;
        
        // 1.3執(zhí)行請(qǐng)求
        NSArray *emps = [_context executeFetchRequest:request error:nil];
        
        // 2.刪除
        for (Employee *e in emps) {
            [_context deleteObject:e];
        }
        
        // 3.保存
        NSError *error = nil;
        [_context save:&error];
        
        if (error) {
            NSLog(@"%@",error);
        }
    
    }
    

二傻寂、CoreData的表關(guān)聯(lián)

準(zhǔn)備工作

  • 創(chuàng)建數(shù)據(jù)庫(kù)

    1. 新建文件,選擇CoreData -> DataModel
    2. 添加實(shí)體(表)携兵,Add Entity 疾掰, 注意:這里根據(jù)關(guān)聯(lián)添加多個(gè)實(shí)體
    3. 給表中添加屬性,點(diǎn)擊Attributes下方的‘+’號(hào)
  • 創(chuàng)建模型文件

    1. 新建文件徐紧,選擇CoreData -> NSManaged Object subclass
    2. 根據(jù)提示静檬,選擇實(shí)體,注意:這里先選擇被關(guān)聯(lián)的實(shí)體并级,最后添加最上層的實(shí)體
  • 通過(guò)代碼拂檩,關(guān)聯(lián)數(shù)據(jù)庫(kù)和實(shí)體

    - (void)viewDidLoad {
        [super viewDidLoad];
    
        /*
         * 關(guān)聯(lián)的時(shí)候,如果本地沒(méi)有數(shù)據(jù)庫(kù)文件嘲碧,Coreadata自己會(huì)創(chuàng)建
         */
        
        // 1. 上下文
        NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
        
        // 2. 上下文關(guān)連數(shù)據(jù)庫(kù)
    
        // 2.1 model模型文件
        NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
        
        // 2.2 持久化存儲(chǔ)調(diào)度器
        // 持久化稻励,把數(shù)據(jù)保存到一個(gè)文件,而不是內(nèi)存
        NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
        
        // 2.3 設(shè)置CoreData數(shù)據(jù)庫(kù)的名字和路徑
        NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *sqlitePath = [doc stringByAppendingPathComponent:@"company.sqlite"];
    
        [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:nil];
        
        context.persistentStoreCoordinator = store;
        _context = context;
    
    }
    

基本操作

  • 添加元素 - Create

    -(IBAction)addEmployee{
    
        // 1. 創(chuàng)建兩個(gè)部門(mén) ios android
        //1.1 iOS部門(mén)
        Department *iosDepart = [NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:_context];
        iosDepart.name = @"ios";
        iosDepart.departNo = @"0001";
        iosDepart.createDate = [NSDate date];
        
        //1.2 Android部門(mén)
        Department *andrDepart = [NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:_context];
        andrDepart.name = @"android";
        andrDepart.departNo = @"0002";
        andrDepart.createDate = [NSDate date];
        
        //2. 創(chuàng)建兩個(gè)員工對(duì)象 zhangsan屬于ios部門(mén) lisi屬于android部門(mén)
        //2.1 zhangsan
        Employee *zhangsan = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context];
        zhangsan.name = @"zhangsan";
        zhangsan.height = @(1.90);
        zhangsan.birthday = [NSDate date];
        zhangsan.depart = iosDepart;
        
        //2.2 lisi
        Employee *lisi = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context];
        lisi.name = @"lisi";
        lisi.height = @2.0;
        lisi.birthday = [NSDate date];
        lisi.depart = andrDepart;
        
        //3. 保存數(shù)據(jù)庫(kù)
        NSError *error = nil;
        [_context save:&error];
        
        if (error) {
            NSLog(@"%@",error);
        }
    }
    
  • 讀取信息 - Read

    -(IBAction)readEmployee{
        
        // 讀取ios部門(mén)的員工
        
        // 1.FectchRequest 抓取請(qǐng)求對(duì)象
        NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
        
        // 2.設(shè)置過(guò)濾條件
        NSPredicate *pre = [NSPredicate predicateWithFormat:@"depart.name = %@",@"android"];
        request.predicate = pre;
        
          // 4.執(zhí)行請(qǐng)求
        NSError *error = nil;
        
        NSArray *emps = [_context executeFetchRequest:request error:&error];
        if (error) {
            NSLog(@"error");
        }
        
        //遍歷員工
        for (Employee *emp in emps) {
            NSLog(@"名字 %@ 部門(mén) %@",emp.name,emp.depart.name);
        }
    }
    
  • 其他功能與前幾種類似呀潭,這里不在贅述

三钉迷、CoreData的模糊查詢

準(zhǔn)備工作和上面類似至非,主要是查詢方式不同

  • 模糊查詢

    -(IBAction)readEmployee{
        // 1.FectchRequest 抓取請(qǐng)求對(duì)象
        NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
    
        // 2.設(shè)置排序
        // 按照身高的升序排序
        NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO];
        request.sortDescriptors = @[heigtSort];
        
        // 3.模糊查詢
        // 3.1 名字以"wang"開(kāi)頭
    //    NSPredicate *pre = [NSPredicate predicateWithFormat:@"name BEGINSWITH %@",@"wangwu1"];
    //    request.predicate = pre;
        
        // 名字以"1"結(jié)尾
    //    NSPredicate *pre = [NSPredicate predicateWithFormat:@"name ENDSWITH %@",@"1"];
    //    request.predicate = pre;
    
        // 名字包含"wu1"
    //    NSPredicate *pre = [NSPredicate predicateWithFormat:@"name CONTAINS %@",@"wu1"];
    //    request.predicate = pre;
        
        // like 匹配
        NSPredicate *pre = [NSPredicate predicateWithFormat:@"name like %@",@"*wu12"];
        request.predicate = pre;
    
        // 4.執(zhí)行請(qǐng)求
        NSError *error = nil;
        NSArray *emps = [_context executeFetchRequest:request error:&error];
        if (error) {
            NSLog(@"error");
        }
        
        //遍歷員工
        for (Employee *emp in emps) {
            NSLog(@"名字 %@ 身高 %@ 生日 %@",emp.name,emp.height,emp.birthday);
        }
    }
    
  • 分頁(yè)查詢

    -(void)pageSeacher{
        // 1. FectchRequest 抓取請(qǐng)求對(duì)象
        NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
        
        // 2. 設(shè)置排序
        // 身高的升序排序
        NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO];
        request.sortDescriptors = @[heigtSort];
        
        // 3. 分頁(yè)查詢
        // 總有共有15數(shù)據(jù)
        // 每次獲取6條數(shù)據(jù)
        // 第一頁(yè) 0,6
        // 第二頁(yè) 6,6
        // 第三頁(yè) 12,6 3條數(shù)據(jù)
        
        // 3.1 分頁(yè)的起始索引
        request.fetchOffset = 12;
        
        // 3.2 分頁(yè)的條數(shù)
        request.fetchLimit = 6;
        
        // 4. 執(zhí)行請(qǐng)求
        NSError *error = nil;
        NSArray *emps = [_context executeFetchRequest:request error:&error];
        if (error) {
            NSLog(@"error");
        }
        
        // 5. 遍歷員工
        for (Employee *emp in emps) {
            NSLog(@"名字 %@ 身高 %@ 生日 %@",emp.name,emp.height,emp.birthday);
        }
    }
    

四钠署、多個(gè)數(shù)據(jù)庫(kù)的使用

注意:

創(chuàng)建多個(gè)數(shù)據(jù)庫(kù),即創(chuàng)建多個(gè)DataModel
一個(gè)數(shù)據(jù)庫(kù)對(duì)應(yīng)一個(gè)上下文
需要根據(jù)bundle名創(chuàng)建上下文
添加或讀取信息荒椭,需要根據(jù)不同的上下文谐鼎,訪問(wèn)不同的實(shí)體

  • 關(guān)聯(lián)數(shù)據(jù)庫(kù)和實(shí)體

    - (void)viewDidLoad {
        [super viewDidLoad];
        
        // 一個(gè)數(shù)據(jù)庫(kù)對(duì)應(yīng)一個(gè)上下文
        _companyContext = [self setupContextWithModelName:@"Company"];
        _weiboContext = [self setupContextWithModelName:@"Weibo"];
    }       
    
    /**
     *  根據(jù)模型文件,返回一個(gè)上下文
     */
    -(NSManagedObjectContext *)setupContextWithModelName:(NSString *)modelName{
        
        // 1. 上下文
        NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
        
        // 2. 上下文關(guān)連數(shù)據(jù)庫(kù)
        // 2.1 model模型文件
        
        // 注意:如果使用下面的方法趣惠,如果 bundles為nil 會(huì)把bundles里面的所有模型文件的表放在一個(gè)數(shù)據(jù)庫(kù)
        //NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
        
        // 改為以下的方法獲壤旯鳌:
        NSURL *companyURL = [[NSBundle mainBundle] URLForResource:modelName withExtension:@"momd"];
        NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:companyURL];
        
        // 2.2 持久化存儲(chǔ)調(diào)度器
        // 持久化身害,把數(shù)據(jù)保存到一個(gè)文件,而不是內(nèi)存
        NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
        
        // 2.3 告訴Coredata數(shù)據(jù)庫(kù)的名字和路徑
        NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *sqliteName = [NSString stringWithFormat:@"%@.sqlite",modelName];
        NSString *sqlitePath = [doc stringByAppendingPathComponent:sqliteName];
    
        [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:nil];
        
        context.persistentStoreCoordinator = store;
        
        // 3. 返回上下文
        return context;
    }
    
  • 添加元素

    -(IBAction)addEmployee{
        // 1. 添加員工
        Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_companyContext];
        emp.name = @"zhagsan";
        emp.height = @2.3;
        emp.birthday = [NSDate date];
        
        // 直接保存數(shù)據(jù)庫(kù)
        [_companyContext save:nil];
        
        // 2. 發(fā)微博
        Status *status =[NSEntityDescription insertNewObjectForEntityForName:@"Status" inManagedObjectContext:_weiboContext];
        
        status.text = @"發(fā)了一條微博草戈!";
        status.createDate = [NSDate date];
        
        [_weiboContext save:nil];
    }
    

聲明

  1. 以上內(nèi)容屬于本人整理的筆記塌鸯,如有錯(cuò)誤的地方希望能告訴我,大家共同進(jìn)步唐片。

  2. 以上內(nèi)容有些段落或語(yǔ)句可能是本人從其他地方Copy而來(lái)丙猬,如有侵權(quán),請(qǐng)及時(shí)告訴我费韭。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末茧球,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子星持,更是在濱河造成了極大的恐慌抢埋,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,589評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件督暂,死亡現(xiàn)場(chǎng)離奇詭異揪垄,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)逻翁,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,615評(píng)論 3 396
  • 文/潘曉璐 我一進(jìn)店門(mén)福侈,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人卢未,你說(shuō)我怎么就攤上這事肪凛。” “怎么了辽社?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,933評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵伟墙,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我滴铅,道長(zhǎng)戳葵,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,976評(píng)論 1 295
  • 正文 為了忘掉前任汉匙,我火速辦了婚禮拱烁,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘噩翠。我一直安慰自己戏自,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,999評(píng)論 6 393
  • 文/花漫 我一把揭開(kāi)白布伤锚。 她就那樣靜靜地躺著擅笔,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上猛们,一...
    開(kāi)封第一講書(shū)人閱讀 51,775評(píng)論 1 307
  • 那天念脯,我揣著相機(jī)與錄音,去河邊找鬼弯淘。 笑死绿店,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的庐橙。 我是一名探鬼主播惯吕,決...
    沈念sama閱讀 40,474評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼怕午!你這毒婦竟也來(lái)了废登?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,359評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤郁惜,失蹤者是張志新(化名)和其女友劉穎堡距,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體兆蕉,經(jīng)...
    沈念sama閱讀 45,854評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡羽戒,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,007評(píng)論 3 338
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了虎韵。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片易稠。...
    茶點(diǎn)故事閱讀 40,146評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖包蓝,靈堂內(nèi)的尸體忽然破棺而出驶社,到底是詐尸還是另有隱情,我是刑警寧澤测萎,帶...
    沈念sama閱讀 35,826評(píng)論 5 346
  • 正文 年R本政府宣布亡电,位于F島的核電站,受9級(jí)特大地震影響硅瞧,放射性物質(zhì)發(fā)生泄漏份乒。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,484評(píng)論 3 331
  • 文/蒙蒙 一腕唧、第九天 我趴在偏房一處隱蔽的房頂上張望或辖。 院中可真熱鬧,春花似錦枣接、人聲如沸颂暇。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,029評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)蟀架。三九已至,卻和暖如春榆骚,著一層夾襖步出監(jiān)牢的瞬間片拍,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,153評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工妓肢, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留捌省,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,420評(píng)論 3 373
  • 正文 我出身青樓碉钠,卻偏偏與公主長(zhǎng)得像纲缓,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子喊废,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,107評(píng)論 2 356

推薦閱讀更多精彩內(nèi)容