CoreData初級使用教程

iOS中的CoreData用起來很是方便,比起SQLite又臭又長而且容易出錯的語句簡直不能再好用,這也是蘋果官方推薦使用的。今天抽空寫個教程給大家參考,也方便自己溫故知新。


一、準(zhǔn)備工作

首先在建立工程時在“use Core Data”前面打鉤


建立工程

這樣系統(tǒng)就會生成一個coreData相關(guān)的文件

coreData文件

然后我們點(diǎn)開這個類就會發(fā)現(xiàn)是一個表格結(jié)構(gòu)的東東,這就是coreData的可視化建模,也是有一定逼格的。
然后我們點(diǎn)擊左下方的Add Entity建立實(shí)體(可以理解為我們經(jīng)常創(chuàng)建的類),并添加幾個屬性

CoreData可視化界面

好了,接下來就是CoreData牛逼的地方,我們選中CoreData對應(yīng)的文件然后選擇Xcode工具欄中的Editor->Create NSManagedObject Subclass...,系統(tǒng)就會生成該實(shí)體對應(yīng)的類

Create NSManagedObject Subclass
生成的類
二、正式使用

系統(tǒng)幫我們生成的類里面該有的不該有的系統(tǒng)已經(jīng)幫我們弄好了,我們只管用就行了。接下來在要使用的類的頭文件中導(dǎo)入該類以及appDelegate.h(方便調(diào)用CoreData方法)

#import "ViewController.h"
#import "AppDelegate.h"
#import "Person.h"


@interface ViewController ()<UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

//用該屬性調(diào)用CoreData命令
@property(nonatomic,strong)AppDelegate *appDelegate;
//存放要顯示的數(shù)據(jù)
@property(nonatomic,strong)NSMutableArray *mutableArray;

@end

為了方便操作以及顯示,我是通過storyboard給界面添加了一個增加數(shù)據(jù)的按鈕,當(dāng)然也可以直接用代碼添加

storyboard中添加按鈕
tableView代理方法
//分區(qū)數(shù)
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
//每個分區(qū)下的行數(shù)

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.mutableArray.count;
}


//定義cell內(nèi)容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //由于這里只是顯示,所以不存在與CoreData交互
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    Person *person = self.mutableArray[indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"姓名:%@,年齡%@",person.name,person.age];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"性別:%@",person.gender];
    return cell;
    
}


增刪改查操作

1 添加數(shù)據(jù)(按鈕的回調(diào)方法)

//添加數(shù)據(jù)
- (IBAction)addData:(id)sender {
    
    //建立一個實(shí)體描述文件
    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.appDelegate.managedObjectContext];
    //通過描述文件創(chuàng)建一個實(shí)體
    Person * person = [[Person alloc]initWithEntity: entityDescription insertIntoManagedObjectContext:self.appDelegate.managedObjectContext];
    
    person.name = @"帥哥";
    person.gender = @"男";
    
    //隨機(jī)生成一個年齡
    int age = arc4random()%20 + 1;
    person.age  = [NSNumber numberWithInt:age];
    //添加到數(shù)據(jù)中
    [self.mutableArray insertObject:person atIndex:0];

    //調(diào)用持久化save方法保存到CoreData中
    [self.appDelegate saveContext];
    //添加到UI下面這句寫成[self.tableView reloadData]也可以
    [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationLeft];
    
}


2刪除數(shù)據(jù)

//滑動后紅色刪除按鈕上顯示的文字
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return @"刪除";
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //刪除情況下
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        Person *person = self.mutableArray[indexPath.row];
        [self.mutableArray removeObject:person];
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        
        //刪除CoreData中的數(shù)據(jù)
        [self.appDelegate.managedObjectContext deleteObject:person];
        
        //持久化一下
        [self.appDelegate saveContext];

    }
  
}

3修改數(shù)據(jù)


//修改數(shù)據(jù)
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    Person *person = self.mutableArray[indexPath.row];

    if ([person.gender isEqualToString:@"男"]) {
        
    person.gender = @"女";
    person.name = @"新名字";
    [self.appDelegate saveContext];
    

    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom];

    }
    
    //詞句代碼作用為點(diǎn)擊cell后的點(diǎn)擊效果完成之后會消失,不會一直顯示選中狀態(tài)
    [self.tableView  deselectRowAtIndexPath:indexPath animated:YES];
    
}

4查詢數(shù)據(jù)
查詢數(shù)據(jù)這塊,CoreData簡直太6了,輸入fet三個字母后然后根據(jù)系統(tǒng)提示按回車瞬間系統(tǒng)給你提供了半個屏幕的代碼,簡直太良心了,我們只需要把相關(guān)信息填進(jìn)去就行

查詢方法
    //查詢數(shù)據(jù)
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.appDelegate.managedObjectContext];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
//謂詞搜索
//    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age = 21", ];
//    [fetchRequest setPredicate:predicate];
    // Specify how the fetched objects should be sorted
//排序方法(這里為按照年齡升序排列)
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.appDelegate.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"數(shù)據(jù)查詢錯誤%@",error);
    }else{

        //查詢到之后要你的操作代碼
     
    }
其他:
viewDidLoad中需要做的事情

估計很多人在做完以上操作后發(fā)現(xiàn)重新運(yùn)行程序后界面上不顯示數(shù)據(jù),很大一部分原因是沒有在viewDidLoad中將CoreData中的數(shù)據(jù)添加到數(shù)據(jù)源中,即,上述查詢方法需在viewDidLoad中執(zhí)行一次并添加到數(shù)據(jù)源中以供顯示

  //初始化
    self.appDelegate = [UIApplication sharedApplication].delegate;
    self.mutableArray = [NSMutableArray array];

//給數(shù)據(jù)源添加數(shù)據(jù)

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.appDelegate.managedObjectContext];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    //    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age = 21", ];
    //    [fetchRequest setPredicate:predicate];
    // Specify how the fetched objects should be sorted
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.appDelegate.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"數(shù)據(jù)查詢錯誤%@",error);
    }else{
        //將查詢到的數(shù)據(jù)添加到數(shù)據(jù)源中
        [self.mutableArray addObjectsFromArray:fetchedObjects];
    }

    
運(yùn)行結(jié)果
三、調(diào)試(查看語句執(zhí)行情況)

有些同學(xué)可能想看一下代碼執(zhí)行情況,這樣也有助于調(diào)試,我們可以按照以下設(shè)置

設(shè)置步驟1
設(shè)置步驟2
添加兩個屬性: "-com.apple.CoreData.SQLDebug"和“1”

這樣設(shè)置完成之后,如果CoreData數(shù)據(jù)有變動,相關(guān)語句會在控制臺打印出來

控制臺內(nèi)容

OVER

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容