CoreData

作者: 人生路02 | 来源:发表于2016-05-25 13:58 被阅读196次

片头曲

CoreData是什么?

  • Core Data 是一个模型层的技术。
  • Core Data 不仅是一个加载、保存数据的框架,它还能和内存中的数据很好的共事。
  • Core Data 提供的最强大的功能之一是它的对象图形管理。
  • Core Data是ORM框架+objects graph,它可以选择sqlite,xml,plist或是其他方式作为持久化方案。

CoreData能做什么?

Core Data 是一种持久化技术,它能将模型对象的状态持久化到磁盘。 Core Data 帮助你建立代表程序状态的模型层。

为什么选择CoreData?

如果你需要其他功能比如redo,undo,数据验证,或是方便的icloud等等额外的功能,就选择core data。

1.基本使用

创建一个coreData应用

1、新建工程,记得勾选Use Core Data

1.png

2、建立好以后可以看到xxx.xcdatamodeld,在这里可以添加实体和实体的属性。需要注意的是:实体名字必须以大写开头。

2.png

3、然后新建一个file,记得是NSManagedObject cubclass

3.png

4、勾选自己建立的工程

4.png

5、勾选建立的实体

5.png

6、next以后我们就可以看到建立好的实体是有4个文件,如图一

图一
这里需要注意的是,xcode7以后建立的都是4个,而7以前的是两个,如图二 图二(偷来的图)

7.添加增删改差四个按钮,及按钮事件处理

 #import "ViewController.h"
 #import "Dog.h"
 #import "AppDelegate.h"
 #import <CoreData/CoreData.h>


@interface ViewController (){
    AppDelegate *app;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    app = [UIApplication sharedApplication].delegate;
    [self createButton];
}

- (void)createButton{
    
    NSArray *array = @[@"增",@"删",@"改",@"查"];
    
    for (int i = 0 ; i<array.count ; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
        btn.frame = CGRectMake(i * 50, 50, 30, 30 );
        [btn setTitle:array[i] forState:UIControlStateNormal];
        btn.backgroundColor = [UIColor orangeColor];
        
        btn.tag = i;
        
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btn];
    }
    
}

- (void)btnClick:(UIButton *)btn{
    
    switch (btn.tag) {
        case 0:
            NSLog(@"增");
            [self coreDataAdd];
            break;
        case 1:
            NSLog(@"删");
            [self coreDataDelete];
            break;
        case 2:
            NSLog(@"改");
            [self coreDataUpdate];
            break;
        case 3:
            NSLog(@"查");
            [self coreDataSelect];
            break;
            
        default:
            break;
    }
}

小插曲


贴代码之前需要了解6个对象:

  • 1、NSManagedObjectContext

    管理对象,上下文,持久性存储模型对象

  • 2、NSManagedObjectModel

    被管理的数据模型,数据结构

  • 3、NSPersistentStoreCoordinator

    连接数据库的

  • 4、NSManagedObject

    被管理的数据记录

  • 5、NSFetchRequest

    数据请求

  • 6、NSEntityDescription

    表格实体结构

  • 此外还需要知道.xcdatamodel文件编译后为.momd或者.mom文件

8.增加

-(void)coreDataAdd{
    // 下面的代码相当于alloc init
    Dog *d = [NSEntityDescription insertNewObjectForEntityForName:@"Dog" inManagedObjectContext:app.managedObjectContext];
    
    d.name = [NSString stringWithFormat:@"花花%d",arc4random()%10];
    d.sex = @"公";
    d.age = [NSNumber numberWithInteger:arc4random()%20];
    
    //将context中存储的数据同步到真实的文件中
    [app.managedObjectContext save:nil];//这个是在AppDelegate中写好的
    
    // BOOL isSave = [[self context]save:nil];//这个save返回bool
    //  if (isSave) {
    //      NSLog(@"ok");
    //  }
    //  else
    //  {
    //      NSLog(@"fs");
    //  }
    
}

9.查询

- (void)coreDataSelect{
    // 读取这个类
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Dog" inManagedObjectContext:app.managedObjectContext];
    // 建立请求
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    // 建立请求是 哪一个类
    [request setEntity:entity];
    
    NSArray *arr = [app.managedObjectContext executeFetchRequest:request error:nil];
    for (Dog *d in arr) {
        NSLog(@"%@",d.name);
    }
    
}

10.删除

- (void)coreDataDelete{
    
//    读取所有狗
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Dog" inManagedObjectContext:app.managedObjectContext];
    
    // 建立请求
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entity];
    
    // 设置检索条件
    NSPredicate *p = [NSPredicate predicateWithFormat:@"name=%@",@"花花8"];
    [request setPredicate:p];
    
    NSArray *array = [app.managedObjectContext executeFetchRequest:request error:nil];
    if (array.count) {
        
        for (Dog *d in array) {
            NSLog(@"%@",d.name);
            [app.managedObjectContext deleteObject:d];
        }
        [app.managedObjectContext save:nil];
        NSLog(@"删除完成");
        
    }else{
        NSLog(@"没有数据");
    }
}

11.修改

- (void)coreDataUpdate{
    
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Dog" inManagedObjectContext:app.managedObjectContext];
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entity];
    
    NSPredicate *p = [NSPredicate predicateWithFormat:@"name!=%@",@"xiaobai107"];
    [request setPredicate:p];
    
    NSArray *arr = [app.managedObjectContext executeFetchRequest:request error:nil];
    if (arr.count) {
        for (Dog *d in arr) {
            NSLog(@"%@",d.name);
            d.name = @"xiaobai107";
        }
        [app.managedObjectContext save:nil];
        NSLog(@"修改成功");
    }else{
        NSLog(@"没有数据");
    }    
}

参考更多1

参考更多2

片尾曲

相关文章

网友评论

      本文标题:CoreData

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