美文网首页
Core Data数据持久化存储

Core Data数据持久化存储

作者: Jian_同学 | 来源:发表于2016-09-28 18:02 被阅读0次

    1.Core Data 含义:

    Core Data(数据库)是数据持久化存储的最适合的方式,通过一系列特性避免使用SQL的一些麻烦,还能合理管理内存。

    Core Data是iOS5之后才出现的一个框架。

    它提供了对象-关系映射(ORM)的功能,即能够将OC对象转化成数据,保存在SQLite数据库文件中,也能够将保存在数据库中的数据还原成OC对象。

    在此数据操作期间,我们不需要编写任何SQL语句,这个有点类似于著名的Hibernate持久化框架,不过功能肯定是没有Hibernate强大的。


    2.Core Data 优点:

    利用Core Data框架,我们就可以轻松地将数据库里面的2条记录转换成2个OC对象,也可以轻松地将2个OC对象保存到数据库中,变成2条表记录,而且不用写一条SQL语句。

    在Core Data,需要进行映射的对象称为实体(entity),而且需要使用Core Data的模型文件来描述app中的所有实体和实体属性。


    3.Core Data 支持的存储类型:

    SQLite、内存、二进制、XML、自定义数据类型


    4.Core Data 的使用:

    例子:对用户输入的信息放入数据库,可对数据进行保存、删除、查看

    创建工程时,勾选Use Core Data选项

    ||

    创建工程后,增加Xcode数据模型文件

    ||

    AppDelegate.h文件中,自动生成

    方法saveContext表示:保存数据到数据库。
    方法applicationDocumentsDirectory表示:应用程序沙盒下的Documents目录路径。

    ||

    建表、设置字段名、建立的表就是一个对象

    ||

    NSManagedObject为每张表新建类(Xcode 8 更改了生成地方)
    简单了解NSManagedObject:

    1.通过Core Data从数据库取出的对象,默认情况下都是NSManagedObject对象。

    2.NSManagedObject的工作模式有点类似于NSDictionary对象,通过键-值对来存取所有的实体属性:
    1> setValue:forKey:存储属性值(属性名为key)
    2> valueForKey:获取属性值(属性名为key)

    ||

    选择数据库

    ||

    选择表

    ||

    生成这几个文件对应相应的数据库,Contactinformation+CoreDataProperties是分类

    ||

    Contactinformation.h文件Demo:

    #import <Foundation/Foundation.h>
    #import <CoreData/CoreData.h> //导入分类
    
    NS_ASSUME_NONNULL_BEGIN
    
    @interface Contactinformation : NSManagedObject
    //返回实体名(类名)
    + (NSString *)entityName;
    @end
    
    NS_ASSUME_NONNULL_END
    
    #import "Contactinformation+CoreDataProperties.h"
    

    ||

    Contactinformation.m文件Demo:

    #import "Contactinformation.h"
    
    @implementation Contactinformation
    + (NSString *)entityName{
        return @"Contactinformation";
    }
    
    //重写description
    - (NSString *)description{
        return [NSString stringWithFormat:@"<name = %@, age = %@, sex = %@, telephone = %@, birthday = %@, adress = %@>",self.name,self.age,self.sex,self.telephone,self.birthday,self.adress];
    }
    @end
    

    ||
    ####### 封装保存、插入、删除数据库的数据方法
    CoreDataManager.h文件的Demo

    //封装保存、插入、删除数据库数据
    #import <Foundation/Foundation.h>
    
    @interface CoreDataManager : NSObject
    //插入
    + (BOOL)insertObjectWithParameter:(NSDictionary *)parameters entityName:(NSString *)entityName;
    //查询
    + (NSArray *)readentityName:(NSString *)entityName predicate:(NSString *)predicateString;
    //删除
    + (BOOL)removeWithEntityName:(NSString *)entityName predicate:(NSString *)predicateString;
    @end
    

    CoreDataManager.m文件的Demo

    #import "CoreDataManager.h"
    #import "AppDelegate.h"
    @implementation CoreDataManager
    
    //委托对象上下文方法
    + (NSManagedObjectContext *)managedObjectContext{
        //获取程序唯一的委托对象上下文,用于存储、查询、删除
        return [(AppDelegate *)[UIApplication sharedApplication].delegate managedObjectContext];
    }
    
    //插入
    + (BOOL)insertObjectWithParameter:(NSDictionary *)parameters entityName:(NSString *)entityName{
        if (entityName.length == 0) { //异常情况判断
            return nil;
        }
        //获取数据(已存在parameters对象中)
        //用实体名实例化模型对象
        NSManagedObject *contect = [NSEntityDescription insertNewObjectForEntityForName:entityName inManagedObjectContext:[self managedObjectContext]]; //用NSManagedObject父类接收
        //把数据存入实体对象
        for (NSString *key in parameters) {
            //KVC (建立的值一样才能用KVC)
            [contect setValue:parameters[key] forKey:key];
        }
        //保存同步文件
        BOOL success = [[self managedObjectContext] save:nil];
        NSLog(@"是否保存成功:%d",success);
        return success;
    }
    //查询
    + (NSArray *)readentityName:(NSString *)entityName predicate:(NSString *)predicateString{
        if (entityName.length == 0) { //异常情况判断
            return nil;
        }
        //1.实例化查询请求类
        NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:entityName];
        //2.配置查询条件(可选操作)
        if (predicateString.length > 0) {
            fetchRequest.predicate = [NSPredicate predicateWithFormat:predicateString]; //年龄等于6才能保存
        }
        //3.执行查询
        NSArray *results = [[self managedObjectContext] executeFetchRequest:fetchRequest error:nil];
        NSLog(@"results = %@",results);
        return results;
    }
    //删除
    + (BOOL)removeWithEntityName:(NSString *)entityName predicate:(NSString *)predicateString{
        if (entityName.length == 0) { //异常情况判断
            return nil;
        }
        NSArray *results = [self readentityName:entityName predicate:predicateString]; //调用查询数据库方法 //1.2.3.步骤在查询数据库方法中
        //4.数据对象的删除 (从数据库中删除)
        for (id object in results) { //所有数据
            [[self managedObjectContext] deleteObject:object];
        }
        //5.保存同步数据
        BOOL success = [[self managedObjectContext] save:nil];
        NSLog(@"是否删除成功:%d",success);
        return success;
    }
    @end
    

    ||

    下面ViewController.m文件是关于iOS界面与如何使用数据库的Demo
    #import "ViewController.h"
    #import "Contactinformation.h"
    #import "AppDelegate.h"
    #import "CoreDataManager.h"
    
    static const NSInteger TEXTFIELD_BASE_TAG = 20;
    
    @interface ViewController ()
    @property (nonatomic, strong) NSArray *keys;
    @end
    
    @implementation ViewController{
        //声明变量
        //委托对象上下文
        NSManagedObjectContext *_context;
    }
    
    //初始化
    - (instancetype)initWithCoder:(NSCoder *)aDecoder{
        self = [super initWithCoder:aDecoder];
        if (self) {
            //获取程序唯一的委托对象上下文,用于存储、查询、删除
            _context = [(AppDelegate *)[UIApplication sharedApplication].delegate managedObjectContext]; //有一个强转否则不认识 //获取程序单例(唯一)
        }
        return self;
    }
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        _keys = @[@"adress",@"name",@"age",@"sex",@"telephone",@"birthday"];
        for (int i = 0; i < 6; i ++) {
            UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(30, (20 + 30 * i) * 2, 100, 30)];
            label1.text = [_keys[i] stringByAppendingString:@":"];
            label1.textAlignment = NSTextAlignmentRight;
            [self.view addSubview:label1];
    
            UITextField *text = [[UITextField alloc] initWithFrame:CGRectMake(140, (20 + 30 * i) * 2, 200, 30)];
            text.backgroundColor = [UIColor whiteColor];
            text.layer.borderColor = [UIColor grayColor].CGColor;
            text.layer.borderWidth = 1;
            text.tag = TEXTFIELD_BASE_TAG + i;
            text.layer.cornerRadius = 8;
            [self.view addSubview:text];
        }
        NSArray *array1 = @[@"save",@"read",@"clear"];
        for (int i = 0; i < 3; i ++) {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
            button.frame = CGRectMake((30 * i + 20) * 3, 400, 50, 30);
            button.backgroundColor = [UIColor clearColor];
            [button setTitle:array1[i] forState:UIControlStateNormal];
            button.titleLabel.font = [UIFont systemFontOfSize:18];
            button.tag = 100 + i;
            [button addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview:button];
        }
    }
    
    
    - (void)button:(UIButton *)sender{
        if (sender.tag == 100) {
            [self insertContext];
        }else if (sender.tag == 101){
            [self readContext];
        }else{
            [self clearContext];
        }
    }
    
    //插入
    - (void)insertContext{
        
        //采用封装
        [CoreDataManager insertObjectWithParameter:[self contactInformation] entityName:[Contactinformation entityName]];
    }
    
    //查询
    - (void)readContext{
        
        //采用封装
        [CoreDataManager readentityName:[Contactinformation entityName] predicate:nil];
    }
    
    //删除
    - (void)clearContext{
        
        //采用封装
        [CoreDataManager removeWithEntityName:[Contactinformation entityName] predicate:nil];
    }
    
    //文本框内容获取方法
    - (NSDictionary *)contactInformation{
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        for (NSInteger i = 0; i < _keys.count; i ++) {
            UITextField *field = (UITextField *)[self.view viewWithTag:TEXTFIELD_BASE_TAG + i];
            if (field.text.length > 0) {
                [dic setObject:field.text forKey:_keys[i]];
            }
        }
        return dic;
    }
    @end
    
    例子演示结果:
    结果演示

    Core Data中的核心对象

    3098145-36fded7ab59714e8.png.jpeg

    相关文章

      网友评论

          本文标题:Core Data数据持久化存储

          本文链接:https://www.haomeiwen.com/subject/ixahyttx.html