CoreData初級使用教程

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


一、準備工作

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


建立工程

這樣系統就會生成一個coreData相關的文件

coreData文件

然后我們點開這個類就會發現是一個表格結構的東東,這就是coreData的可視化建模,也是有一定逼格的。
然后我們點擊左下方的Add Entity建立實體(可以理解為我們經常創建的類),并添加幾個屬性

CoreData可視化界面

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

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

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

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


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

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

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

@end

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

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

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


//定義cell內容
-(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 添加數據(按鈕的回調方法)

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

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


2刪除數據

//滑動后紅色刪除按鈕上顯示的文字
-(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中的數據
        [self.appDelegate.managedObjectContext deleteObject:person];
        
        //持久化一下
        [self.appDelegate saveContext];

    }
  
}

3修改數據


//修改數據
-(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];

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

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

查詢方法
    //查詢數據
    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(@"數據查詢錯誤%@",error);
    }else{

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

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

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

//給數據源添加數據

    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(@"數據查詢錯誤%@",error);
    }else{
        //將查詢到的數據添加到數據源中
        [self.mutableArray addObjectsFromArray:fetchedObjects];
    }

    
運行結果
三、調試(查看語句執行情況)

有些同學可能想看一下代碼執行情況,這樣也有助于調試,我們可以按照以下設置

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

這樣設置完成之后,如果CoreData數據有變動,相關語句會在控制臺打印出來

控制臺內容

OVER

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容