iOS数据存储篇-CoreData使用教程

简介

CoreData是一个框架,可以将咱们的OC对象和存储在SQLite文件中的数据进行互相转换。并且做这些操作,你不需要写任何SQLite语句。

和ORM的区别

ORM-对象关系映射
CoreData-它具备ORM的某些功能

必备知识

  • NSManagedObject
    从CoreData中取出来对象,默认都是NSManagedObject对象,通过键值对来存取所有的实体属性,相当于数据库中的表格记录

  • NSManagedObjectContext
    负责应用与数据库之间的交互,增删改查基本操作都要用到

  • NSManagedObjectModel
    被管理的数据模型,可以添加实体及实体的属性,若新建的项目带CoreData,即为XXX.xcdatamodeld

  • NSPersistentStoreCoordinator
    数据库的连接器,设置数据存储的名字,位置,存储方式等

  • NSFetchRequest
    获取数据时的请求

  • NSEntityDescription
    用来描述实体

简单使用(创建工程时带CoreData)

  • 新建工程时勾选Use Core Data,则AppDelegate.h中

在AppDelegate.m(项目名称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();
        }
    }
}

  • 建好后你会发现工程中多了XXX.xcdatamodeld,我们需要在这里添加实体(首字母大写)和实体的属性。
  • 因为利用Core Data取出的实体都是NSManagedObject类型,可以通过键值对来存取对象,但如果还要做其他操作,则需要创建NSManagedObject的子类,建时勾选工程和实体,建好后会发现工程中多了四个文件
  • 导入CoreData.framework和头文件<CoreData/CoreData.h>

  • 代码实现
    0-创建实体Person,有两个属性name和age


1-因为创建工程时带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.创建实体,并为实体属性赋值
Person *p = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:context];
p.name = [NSString stringWithFormat:@"大倩倩%d",arc4random()%10];
p.age = [NSString stringWithFormat:@"%d",arc4random()%60];

2.保存数据
[context save:nil];


***************************************************************


3.查询
建立请求
NSFetchRequest *request = [[NSFetchRequest alloc] init] ;
读取实体
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:context];
请求连接实体
request.entity = entity;
遍历所有实体,将每个实体的信息存放在数组中
NSArray *arr = [context executeFetchRequest:request error:nil];
打印
        for (Person *p in arr)
        {
            NSLog(@"name=%@,age=%@", p.name,p.age);
        }

因为是写在viewDidLoad中,每运行一次增加一条数据


3-删

1.建立请求,连接实体
NSFetchRequest *request = [[NSFetchRequest alloc] init] ;
request.entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:context];

2.设置条件过滤(搜索age属性中包含”12“的那条记录,注意等号必须加,可以有空格,也可以是==)
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age=%@", @"12"];
request.predicate = predicate;

3.遍历所有实体,将每个实体的信息存放在数组中
NSArray *arr = [context executeFetchRequest:request error:nil];

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

4-改

1.建立请求,连接实体
NSFetchRequest *request = [[NSFetchRequest alloc] init] ;
request.entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:context];

2.设置条件过滤(搜索所有name属性不为“大倩倩1”的数据)
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name!=%@", @"大倩倩1"];
request.predicate = predicate;

3.遍历所有实体,将每个实体的信息存放在数组中
NSArray *arr = [app.managedObjectContext executeFetchRequest:request error:nil];

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

简单使用(创建工程时不带Core Data)

  • 新建Data Model
  • 我建了QQModel(QQModel.xcdatamodeld),并建了一个Animal实体和kind属性
  • 为QQModel建立NSManagedObject的子类
  • 写代码

1-导入CoreData.framework

2-新建类CoreDataBase,继承自NSObject,将创建工程时使用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

注意,这两个名字必须一致

不然会报如下错误

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] ;
    //设置要查询的实体
    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中调用

#import "CoreDataBase.h"
- (void)viewDidLoad
{
    [super viewDidLoad];
    CoreDataBase  *base = [[CoreDataBase alloc] init];
    [base insertCoreData:@"虎"];
    [base queryCoreData];
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335

推荐阅读更多精彩内容