iOS數(shù)據(jù)存儲(chǔ)篇-CoreData使用教程

簡(jiǎn)介

CoreData是一個(gè)框架,可以將咱們的OC對(duì)象和存儲(chǔ)在SQLite文件中的數(shù)據(jù)進(jìn)行互相轉(zhuǎn)換。并且做這些操作,你不需要寫任何SQLite語(yǔ)句。

和ORM的區(qū)別

ORM-對(duì)象關(guān)系映射
CoreData-它具備ORM的某些功能

必備知識(shí)

  • NSManagedObject
    從CoreData中取出來對(duì)象,默認(rèn)都是NSManagedObject對(duì)象,通過鍵值對(duì)來存取所有的實(shí)體屬性,相當(dāng)于數(shù)據(jù)庫(kù)中的表格記錄

  • NSManagedObjectContext
    負(fù)責(zé)應(yīng)用與數(shù)據(jù)庫(kù)之間的交互,增刪改查基本操作都要用到

  • NSManagedObjectModel
    被管理的數(shù)據(jù)模型,可以添加實(shí)體及實(shí)體的屬性,若新建的項(xiàng)目帶CoreData,即為XXX.xcdatamodeld

  • NSPersistentStoreCoordinator
    數(shù)據(jù)庫(kù)的連接器,設(shè)置數(shù)據(jù)存儲(chǔ)的名字,位置,存儲(chǔ)方式等

  • NSFetchRequest
    獲取數(shù)據(jù)時(shí)的請(qǐng)求

  • NSEntityDescription
    用來描述實(shí)體

簡(jiǎn)單使用(創(chuàng)建工程時(shí)帶CoreData)

  • 新建工程時(shí)勾選Use Core Data,則AppDelegate.h中

在AppDelegate.m(項(xiàng)目名稱BBB,自帶的Model為BBB.xcdatamodeld)中

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "iii.BBB" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"BBB" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"BBB.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

  • 建好后你會(huì)發(fā)現(xiàn)工程中多了XXX.xcdatamodeld,我們需要在這里添加實(shí)體(首字母大寫)和實(shí)體的屬性。
  • 因?yàn)槔肅ore Data取出的實(shí)體都是NSManagedObject類型,可以通過鍵值對(duì)來存取對(duì)象,但如果還要做其他操作,則需要?jiǎng)?chuàng)建NSManagedObject的子類,建時(shí)勾選工程和實(shí)體,建好后會(huì)發(fā)現(xiàn)工程中多了四個(gè)文件
  • 導(dǎo)入CoreData.framework和頭文件<CoreData/CoreData.h>

  • 代碼實(shí)現(xiàn)
    0-創(chuàng)建實(shí)體Person,有兩個(gè)屬性name和age


1-因?yàn)閯?chuàng)建工程時(shí)帶Core Data,AppDelegate中含了我們需要用的,所以在要操作的控制器中

#import <CoreData/CoreData.h>
#import "AppDelegate.h"
#import "Person.h"
@interface ViewController ()
{
    AppDelegate  *app;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    app =[UIApplication sharedApplication].delegate;
    NSManagedObjectContext *context = app.managedObjectContext;
}

2-增

1.創(chuàng)建實(shí)體,并為實(shí)體屬性賦值
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.查詢
建立請(qǐng)求
NSFetchRequest *request = [[NSFetchRequest alloc] init] ;
讀取實(shí)體
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:context];
請(qǐng)求連接實(shí)體
request.entity = entity;
遍歷所有實(shí)體,將每個(gè)實(shí)體的信息存放在數(shù)組中
NSArray *arr = [context executeFetchRequest:request error:nil];
打印
        for (Person *p in arr)
        {
            NSLog(@"name=%@,age=%@", p.name,p.age);
        }

因?yàn)槭菍懺趘iewDidLoad中,每運(yùn)行一次增加一條數(shù)據(jù)


3-刪

1.建立請(qǐng)求,連接實(shí)體
NSFetchRequest *request = [[NSFetchRequest alloc] init] ;
request.entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:context];

2.設(shè)置條件過濾(搜索age屬性中包含”12“的那條記錄,注意等號(hào)必須加,可以有空格,也可以是==)
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age=%@", @"12"];
request.predicate = predicate;

3.遍歷所有實(shí)體,將每個(gè)實(shí)體的信息存放在數(shù)組中
NSArray *arr = [context executeFetchRequest:request error:nil];

4.刪除并保存
    if(arr.count)
    {
        for (Person *p in arr)
        {
            [context deleteObject:p];
            
        }
        //保存
        [context save:nil];
    }
    

4-改

1.建立請(qǐng)求,連接實(shí)體
NSFetchRequest *request = [[NSFetchRequest alloc] init] ;
request.entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:context];

2.設(shè)置條件過濾(搜索所有name屬性不為“大倩倩1”的數(shù)據(jù))
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name!=%@", @"大倩倩1"];
request.predicate = predicate;

3.遍歷所有實(shí)體,將每個(gè)實(shí)體的信息存放在數(shù)組中
NSArray *arr = [app.managedObjectContext executeFetchRequest:request error:nil];

4.更改并保存
    if(arr.count)
    {
        for (Person *p in arr)
        {
            p.name = @"更改";
            
        }
        //保存
        [context save:nil];
    }
    else
    {
        NSLog(@"無檢索");
    }

簡(jiǎn)單使用(創(chuàng)建工程時(shí)不帶Core Data)

  • 新建Data Model
  • 我建了QQModel(QQModel.xcdatamodeld),并建了一個(gè)Animal實(shí)體和kind屬性
  • 為QQModel建立NSManagedObject的子類
  • 寫代碼

1-導(dǎo)入CoreData.framework

2-新建類CoreDataBase,繼承自NSObject,將創(chuàng)建工程時(shí)使用CoreData中,AppDelegate自帶的代碼粘貼過來

1. CoreDataBase.h

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@interface CoreDataBase : NSObject
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;

- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;

- (void)insertCoreData:(NSString *)str;
- (void)queryCoreData;
@end


2. CoreDataBase.m
#import "CoreDataBase.h"

@implementation CoreDataBase

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "iii.BBB" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"QQModel" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"BBB.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

@end

注意,這兩個(gè)名字必須一致

不然會(huì)報(bào)如下錯(cuò)誤

3-在CoreDataBase中封裝增加和查詢方法

1. CoreDataBase.h
#import "Animal.h"
- (void)insertCoreData:(NSString *)str;//增加
- (void)queryCoreData;  //查詢


2. CoreDataBase.m

//增減
- (void)insertCoreData:(NSString *)str
{
    NSManagedObjectContext *context = [self managedObjectContext];
    Animal *a = [NSEntityDescription insertNewObjectForEntityForName:@"Animal" inManagedObjectContext:context];
    a.kind = str;
    [context save:nil];
    
}

//查詢
- (void)queryCoreData
{
    NSManagedObjectContext *context = [self managedObjectContext];
    NSFetchRequest *request = [[NSFetchRequest alloc] init] ;
    //設(shè)置要查詢的實(shí)體
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Animal" inManagedObjectContext:context];
    request.entity = entity;
    
    
    NSArray *arr = [context executeFetchRequest:request error:nil];
    for (Animal *a in arr)
    {
        NSLog(@"name=%@,", a.kind);
    }
}

4-在ViewController中調(diào)用

#import "CoreDataBase.h"
- (void)viewDidLoad
{
    [super viewDidLoad];
    CoreDataBase  *base = [[CoreDataBase alloc] init];
    [base insertCoreData:@"虎"];
    [base queryCoreData];
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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