我要娶你做我的CoreData!

一、CoreData的簡單使用

準備工作

  • 創建數據庫

    1. 新建文件,選擇CoreData -> DataModel
    2. 添加實體(表),Add Entity
    3. 給表中添加屬性,點擊Attributes下方的‘+’
  • 創建模型文件

    1. 新建文件,選擇CoreData -> NSManaged Object subclass
    2. 根據提示,選擇實體
  • 通過代碼,關聯數據庫和實體

    - (void)viewDidLoad {
        [super viewDidLoad];
    
        /*
         * 關聯的時候,如果本地沒有數據庫文件,Coreadata自己會創建
         */
        
        // 1. 上下文
        NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
        
        // 2. 上下文關連數據庫
    
        // 2.1 model模型文件
        NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
        
        // 2.2 持久化存儲調度器
        // 持久化,把數據保存到一個文件,而不是內存
        NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
        
        // 2.3 設置CoreData數據庫的名字和路徑
        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{
    
        // 創建一個員工對象 
        //Employee *emp = [[Employee alloc] init]; 不能用此方法創建
        Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context];
        emp.name = @"wangwu";
        emp.height = @1.80;
        emp.birthday = [NSDate date];
        
        // 直接保存數據庫
        NSError *error = nil;
        [_context save:&error];
        
        if (error) {
            NSLog(@"%@",error);
        }
    }     
    
  • 讀取數據 - Read

    -(IBAction)readEmployee{
        
        // 1.FetchRequest 獲取請求對象
        NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
        
        // 2.設置過濾條件
        // 查找zhangsan
        NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",
                            @"zhangsan"];
        request.predicate = pre;
        
        // 3.設置排序
        // 身高的升序排序
        NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO];
        request.sortDescriptors = @[heigtSort];
        
        // 4.執行請求
        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);
        }
    }
    
  • 修改數據 - Update

    -(IBAction)updateEmployee{
        // 改變zhangsan的身高為2m
        
        // 1.查找到zhangsan
        // 1.1FectchRequest 抓取請求對象
        NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
        
        // 1.2設置過濾條件
        // 查找zhangsan
        NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@", @"zhangsan"];
        request.predicate = pre;
    
        // 1.3執行請求
        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);
        }
    }
    
  • 刪除數據 - Delete

    -(IBAction)deleteEmployee{
        
        // 刪除 lisi
        
        // 1.查找lisi
        // 1.1FectchRequest 抓取請求對象
        NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
        
        // 1.2設置過濾條件
        // 查找zhangsan
        NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",
                            @"lisi"];
        request.predicate = pre;
        
        // 1.3執行請求
        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的表關聯

準備工作

  • 創建數據庫

    1. 新建文件,選擇CoreData -> DataModel
    2. 添加實體(表),Add Entity注意:這里根據關聯添加多個實體
    3. 給表中添加屬性,點擊Attributes下方的‘+’
  • 創建模型文件

    1. 新建文件,選擇CoreData -> NSManaged Object subclass
    2. 根據提示,選擇實體,注意:這里先選擇被關聯的實體,最后添加最上層的實體
  • 通過代碼,關聯數據庫和實體

    - (void)viewDidLoad {
        [super viewDidLoad];
    
        /*
         * 關聯的時候,如果本地沒有數據庫文件,Coreadata自己會創建
         */
        
        // 1. 上下文
        NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
        
        // 2. 上下文關連數據庫
    
        // 2.1 model模型文件
        NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
        
        // 2.2 持久化存儲調度器
        // 持久化,把數據保存到一個文件,而不是內存
        NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
        
        // 2.3 設置CoreData數據庫的名字和路徑
        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. 創建兩個部門 ios android
        //1.1 iOS部門
        Department *iosDepart = [NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:_context];
        iosDepart.name = @"ios";
        iosDepart.departNo = @"0001";
        iosDepart.createDate = [NSDate date];
        
        //1.2 Android部門
        Department *andrDepart = [NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:_context];
        andrDepart.name = @"android";
        andrDepart.departNo = @"0002";
        andrDepart.createDate = [NSDate date];
        
        //2. 創建兩個員工對象 zhangsan屬于ios部門 lisi屬于android部門
        //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. 保存數據庫
        NSError *error = nil;
        [_context save:&error];
        
        if (error) {
            NSLog(@"%@",error);
        }
    }
    
  • 讀取信息 - Read

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

三、CoreData的模糊查詢

準備工作和上面類似,主要是查詢方式不同

  • 模糊查詢

    -(IBAction)readEmployee{
        // 1.FectchRequest 抓取請求對象
        NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
    
        // 2.設置排序
        // 按照身高的升序排序
        NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO];
        request.sortDescriptors = @[heigtSort];
        
        // 3.模糊查詢
        // 3.1 名字以"wang"開頭
    //    NSPredicate *pre = [NSPredicate predicateWithFormat:@"name BEGINSWITH %@",@"wangwu1"];
    //    request.predicate = pre;
        
        // 名字以"1"結尾
    //    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.執行請求
        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);
        }
    }
    
  • 分頁查詢

    -(void)pageSeacher{
        // 1. FectchRequest 抓取請求對象
        NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
        
        // 2. 設置排序
        // 身高的升序排序
        NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO];
        request.sortDescriptors = @[heigtSort];
        
        // 3. 分頁查詢
        // 總有共有15數據
        // 每次獲取6條數據
        // 第一頁 0,6
        // 第二頁 6,6
        // 第三頁 12,6 3條數據
        
        // 3.1 分頁的起始索引
        request.fetchOffset = 12;
        
        // 3.2 分頁的條數
        request.fetchLimit = 6;
        
        // 4. 執行請求
        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);
        }
    }
    

四、多個數據庫的使用

注意:

創建多個數據庫,即創建多個DataModel
一個數據庫對應一個上下文
需要根據bundle名創建上下文
添加或讀取信息,需要根據不同的上下文,訪問不同的實體

  • 關聯數據庫和實體

    - (void)viewDidLoad {
        [super viewDidLoad];
        
        // 一個數據庫對應一個上下文
        _companyContext = [self setupContextWithModelName:@"Company"];
        _weiboContext = [self setupContextWithModelName:@"Weibo"];
    }       
    
    /**
     *  根據模型文件,返回一個上下文
     */
    -(NSManagedObjectContext *)setupContextWithModelName:(NSString *)modelName{
        
        // 1. 上下文
        NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
        
        // 2. 上下文關連數據庫
        // 2.1 model模型文件
        
        // 注意:如果使用下面的方法,如果 bundles為nil 會把bundles里面的所有模型文件的表放在一個數據庫
        //NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
        
        // 改為以下的方法獲取:
        NSURL *companyURL = [[NSBundle mainBundle] URLForResource:modelName withExtension:@"momd"];
        NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:companyURL];
        
        // 2.2 持久化存儲調度器
        // 持久化,把數據保存到一個文件,而不是內存
        NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
        
        // 2.3 告訴Coredata數據庫的名字和路徑
        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];
        
        // 直接保存數據庫
        [_companyContext save:nil];
        
        // 2. 發微博
        Status *status =[NSEntityDescription insertNewObjectForEntityForName:@"Status" inManagedObjectContext:_weiboContext];
        
        status.text = @"發了一條微博!";
        status.createDate = [NSDate date];
        
        [_weiboContext save:nil];
    }
    

聲明

  1. 以上內容屬于本人整理的筆記,如有錯誤的地方希望能告訴我,大家共同進步。

  2. 以上內容有些段落或語句可能是本人從其他地方Copy而來,如有侵權,請及時告訴我。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,156評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,401評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,069評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,873評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,635評論 6 408
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,128評論 1 323
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,203評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,365評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,881評論 1 334
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,733評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,935評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,475評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,172評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,582評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,821評論 1 282
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,595評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,908評論 2 372

推薦閱讀更多精彩內容