CoreData简单使用

github地址
借鉴文章

概念介绍
coreData
NSManagedObjectContext 管理对象,上下文,持久性存储模型对象,处理数据与应用的交互,托管对象上下文,数据库的大多数操作是在这个类操作
NSManagedObjectModel 被管理的数据模型,数据结构,托管对象模型,其中一个托管对象模型关联到一个模型文件,里面存储着数据库的数据结构。
NSPersistentStoreCoordinator 添加数据库,设置数据存储的名字,位置,存储方式,持久化存储协调器,主要负责协调上下文存储的区域的关系。
NSManagedObject 被管理的数据记录,托管对象类,其中CoreData里面的托管对象都会继承此类。
NSFetchRequest 数据请求
NSEntityDescription 表格实体结构
NSPredicate 过滤条件,找到要修改的对象

model文件参考

#import 
#import 
NS_ASSUME_NONNULL_BEGIN

@interface User : NSManagedObject
//属性的类型一旦创建不可修改,如需修改,必须删除APP中旧的数据库文件,否则崩溃
@property (nonatomic,strong) NSString* name;
@property (nonatomic,assign) BOOL sex;
@property (nonatomic,strong)UIImageView* image;
@property (nonatomic,strong) NSString* aID;
@property (nonatomic,assign) float height;//和CoreDataProject.xcdatamodeld中的UserEntity中的类型一致,不可以是CGFloat
@property (nonatomic,assign) NSInteger age;
@end

NS_ASSUME_NONNULL_END

ViewController文件参考

//
//  ViewController.m
//  CoreDataProject
//
//  Created by alex black on 2019/3/20.
//  Copyright © 2019 JTB.com. All rights reserved.
//

#import "ViewController.h"
#import 
#import "AppDelegate.h"
#import "User.h"
@interface ViewController ()
@property (nonatomic,strong) NSManagedObjectContext *context;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    //CoreDataProject.xcdatamodeld文件 编译后就是 CoreDataProject.momd 所以名字要对应
    NSURL *modelPath = [[NSBundle mainBundle] URLForResource:@"CoreDataProject" withExtension:@"momd"];
    NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelPath];
    NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];

    NSString *dataPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    dataPath = [dataPath stringByAppendingFormat:@"/People.sqlite"];//自己定义的数据库名字 千万别忘记加/ 否则真机无法创建相应文件
    [coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:dataPath] options:nil error:nil];

    context.persistentStoreCoordinator = coordinator;
    self.context = context;
}
#pragma mark - 插入操作
- (void)insertMethod:(NSManagedObjectContext*)context
{
    //@"UserEntity" 要和 CoreDataProject.xcdatamodeld文件中定义的model名字一样  特别注意:User中的属性描述必须和UserEntity的属性描述一致,否则无法存入,例如User的height是CGFloat 而 UserEntity的height是Float,类型不一致无法存入信息,也无法修改
    User* obj =  (User*)[NSEntityDescription insertNewObjectForEntityForName:@"UserEntity" inManagedObjectContext:context];
    obj.name = @"ee";
    obj.sex = YES;
    obj.age = 18;
    obj.height = 180;
    
    User* obj2 =  (User*)[NSEntityDescription insertNewObjectForEntityForName:@"UserEntity" inManagedObjectContext:context];
    obj2.name = @"pp";
    obj2.sex = NO;
    obj2.age = 16;
    obj2.height = 160;
    
    NSError *error1;
    if (context.hasChanges) {
        [context save:&error1];
    }
    if (error1) {
        NSLog(@"error1 = %@",error1);
    }
}
#pragma mark - 删除操作
- (void)deleteMethod:(NSManagedObjectContext*)context{
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"UserEntity"];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@",@"ee"];
    request.predicate = predicate;
    NSError *error2;
    NSArray *deleteArr = [context executeFetchRequest:request error:&error2];
    [deleteArr enumerateObjectsUsingBlock:^(User * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [context deleteObject:(NSManagedObject*)obj];
    }];
    if ([context hasChanges]) {
        [context save:nil];
    }
    if (error2) {
        NSLog(@"%@",error2);
    }
}
#pragma mark - 修改操作
- (void)changeMethod:(NSManagedObjectContext*)context{
    NSFetchRequest *request1 = [NSFetchRequest fetchRequestWithEntityName:@"UserEntity"];
    NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"name=%@",@"pp"];
    request1.predicate = predicate1;
    NSError *error3 = nil;
    NSArray *chageArr = [context executeFetchRequest:request1 error:&error3];
    [chageArr enumerateObjectsUsingBlock:^(User * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.height = 133;
    }];
    if ([context hasChanges]) {
        [context save:nil];
    }
    if (error3) {
        NSLog(@"%@",error3);
    }
}
#pragma mark - 查找操作
- (void)queryMethod:(NSManagedObjectContext*)context{
    NSFetchRequest *request4 = [NSFetchRequest fetchRequestWithEntityName:@"UserEntity"];
    NSError *error4 = nil;
    NSArray *quertArr = [context executeFetchRequest:request4 error:&error4];
    [quertArr enumerateObjectsUsingBlock:^(User * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSLog(@"User Name : %@, Height : %@, age : %d", obj.name, @(obj.height), obj.age);
    }];
    
    // 错误处理
    if (error4) {
        NSLog(@"%@", error4);
    }
}
- (IBAction)buttonClick:(UIButton *)sender {
    if (sender.tag == 1) {
        [self insertMethod:self.context];
    }else if (sender.tag == 2) {
        [self deleteMethod:self.context];
    }else if (sender.tag == 3) {
        [self changeMethod:self.context];
    }else if (sender.tag == 4) {
        [self queryMethod:self.context];
    }
}

@end

你可能感兴趣的:(CoreData简单使用)