iOS CoreData总结

相关主要类:

NSManagedObjectContext 管理对象,上下文,持久性存储模型对象,处理数据与应用的交互
NSManagedObjectModel 被管理的数据模型,数据结构
NSPersistentStoreCoordinator 添加数据库,设置数据存储的名字,位置,存储方式
NSManagedObject 被管理的数据记录
NSFetchRequest 数据请求
NSEntityDescription 表格实体结构

相关操作:

Editor -> Add Model Version : 创建新的数据库

Editor -> Create NSManagerObject SubClass 创建模型对象文件

注意点:

1.Codegen 属性要设置为 None ,不然再手动生成显示的模型对象文件多报错。(默认是隐式文件,但是使用实体类时,无法引用文件)

 2.

    //    创建托管对象模型 @“lwCoreDataDemo”是CoreData的文件名;@“momd”是.xcdatamodel文件,用数据模型编辑器编辑编译后为.momd或.mom文件,所以就写@“momd”,
    NSURL *modelpath = [[NSBundle mainBundle] URLForResource:@"lwCoreDataDemo" withExtension:@"momd"];
    NSLog(@"------modelpath:%@",modelpath);
    NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelpath];

1.初始化

2.增删改查操作

3.数据量迁移:主要设置,不然无法找到 当前的模型文件

  //请求自动轻量级迁移
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                             [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                             [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
                             nil];
    [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:datapath] options:options error:nil];

4.多表操作

//    多表插入
    Student * student = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:_context];
    student.age = arc4random()%10;
    student.name = @"jack";
    
    Course *course = [NSEntityDescription insertNewObjectForEntityForName:@"Course" inManagedObjectContext:_context];
    course.course_id = arc4random()%20;
    course.course_name = @"英语";
//    [student addStu_course:[NSSet setWithObject:course]];
    student.stu_course = [NSSet setWithObject:course];
    
    Classes *classes = [NSEntityDescription insertNewObjectForEntityForName:@"Classes" inManagedObjectContext:_context];
    classes.class_name = [NSString stringWithFormat:@"高二(%u)班",arc4random()%3];
    classes.class_id = arc4random()%10;
    student.stu_classes = classes;
    
 //    多表查询
    NSFetchRequest *requst1 = [NSFetchRequest fetchRequestWithEntityName:@"Student"];
    requst1.predicate = [NSPredicate predicateWithFormat:@"stu_classes.class_name=%@",@"高二(1)班"];
    
    NSArray *res1 =  [_context executeFetchRequest:requst1 error:nil];
    [res1 enumerateObjectsUsingBlock:^(Student * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSLog(@"Student:[name:%@,age:%hd]",obj.name,obj.age);
    }];

5.代码

封装的工具类:

.h文件

//
//  LWCoreDataManager.h
//  lwCoreDataDemo
//
//  Created by LWQ on 2020/6/29.
//  Copyright © 2020 LWQ. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#import "Person+CoreDataClass.h"
#import "Student+CoreDataClass.h"
#import "Classes+CoreDataClass.h"
#import "Course+CoreDataClass.h"

@interface LWCoreDataManager : NSObject
@property (nonatomic, strong) NSManagedObjectContext * context;

+ (instancetype)share;

- (void)insert;
- (NSArray<Person *>*)query;
- (void)delete;
- (void)update;

+ (NSString *)personString:(Person *)p;
@end
LWCoreDataManager.h

.m文件

//
//  LWCoreDataManager.m
//  lwCoreDataDemo
//
//  Created by LWQ on 2020/6/29.
//  Copyright © 2020 LWQ. All rights reserved.
//

#import "LWCoreDataManager.h"

@implementation LWCoreDataManager

+ (instancetype)share
{
    static LWCoreDataManager *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[LWCoreDataManager alloc] init];
        [instance installConfigure];
    });
    return instance;
}

//安装配置
- (void)installConfigure
{
    //    创建托管上下文对象
    _context = [[NSManagedObjectContext alloc] initWithConcurrencyType:(NSMainQueueConcurrencyType)];
    
    //    创建托管对象模型
    NSURL *modelpath = [[NSBundle mainBundle] URLForResource:@"lwCoreDataDemo" withExtension:@"momd"];
    NSLog(@"------modelpath:%@",modelpath);
    NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelpath];
    
    //    创建持久化存储调度器
    NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
    
    //    创建数据库文件并关联持久化存储调度器
    NSString *datapath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    datapath = [datapath stringByAppendingFormat:@"/%@.sqlite",@"lwCoreDataDemo"];
    NSLog(@"------datapath:%@",datapath);
    
    //请求自动轻量级迁移
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                             [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                             [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
                             nil];
    [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:datapath] options:options error:nil];
    
    // 上下文对象设置属性为持久化存储器
    _context.persistentStoreCoordinator = store;
    
}

//插入插入
- (void)insert
{
//    单表插入
//    Person * model = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:_context];
//    NSLog(@"--------mode:%@",model.class);
//
//    model.age = arc4random()%20;
//    model.name = @"lwq";
//    model.address = @"bj";
//    model.num = arc4random()&10;
    
    
//    多表插入
    Student * student = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:_context];
    student.age = arc4random()%10;
    student.name = @"jack";
    
    Course *course = [NSEntityDescription insertNewObjectForEntityForName:@"Course" inManagedObjectContext:_context];
    course.course_id = arc4random()%20;
    course.course_name = @"英语";
//    [student addStu_course:[NSSet setWithObject:course]];
    student.stu_course = [NSSet setWithObject:course];
    
    Classes *classes = [NSEntityDescription insertNewObjectForEntityForName:@"Classes" inManagedObjectContext:_context];
    classes.class_name = [NSString stringWithFormat:@"高二(%u)班",arc4random()%3];
    classes.class_id = arc4random()%10;
    student.stu_classes = classes;
    
    
    NSError *error ;
    if ([_context hasChanges]) {
        [_context save:&error];
    }
    if (error) {
        NSLog(@"插入数据失败");
    }
    NSLog(@"插入数据成功");
}

// 查询
- (NSArray<Person *>*)query
{
    //    多表查询
    NSFetchRequest *requst1 = [NSFetchRequest fetchRequestWithEntityName:@"Student"];
    requst1.predicate = [NSPredicate predicateWithFormat:@"stu_classes.class_name=%@",@"高二(1)班"];
    
    NSArray *res1 =  [_context executeFetchRequest:requst1 error:nil];
    [res1 enumerateObjectsUsingBlock:^(Student * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSLog(@"Student:[name:%@,age:%hd]",obj.name,obj.age);
    }];

    //    单表查询
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
    NSArray<Person *> *res =  [_context executeFetchRequest:request error:nil];
    [res enumerateObjectsUsingBlock:^(Person * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSLog(@"%@",[LWCoreDataManager personString:obj]);
    }];
    return res;
}

//删除操作
- (void)delete
{
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"age < 10"];
    request.predicate = pred;
    
    NSArray *res = [_context executeFetchRequest:request error:nil];
    [res enumerateObjectsUsingBlock:^(Person *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [_context deleteObject:obj];
    }];
    NSError *error;
    if ([_context hasChanges]) {
        [_context save:&error];
    }
    if (error) {
        NSLog(@"删除数据失败");
    }
    NSLog(@"删除i数据成功");
}

//更新操作
- (void)update
{
    NSFetchRequest *request =  [NSFetchRequest fetchRequestWithEntityName:@"Person"];
    
    request.predicate = [NSPredicate predicateWithFormat:@"age >10"];
    
    NSArray *res = [_context executeFetchRequest:request error:nil];
    
    [res enumerateObjectsUsingBlock:^(Person*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.age = 12;
        obj.name = @"rose";
        obj.num = 100;
    }];
    NSError *error;
    if ([_context hasChanges]) {
        [_context save:&error];
    }
    if (error) {
        NSLog(@"更新数据数据失败");
    }
    NSLog(@"更新数据成功");
}


+ (NSString *)personString:(Person *)p
{
    return [NSString stringWithFormat:@"Person:[age:%hd,name:%@,address:%@,num:%hd]",p.age,p.name,p.address,p.num];
}

@end
LWCoreDataManager.m

CoreData多线程的相关:

https://www.jianshu.com/p/283e67ba12a3

原文地址:https://www.cnblogs.com/liuwenqiang/p/13208160.html