数据存储:CoreData

CoreData的简单使用介绍(已User表为例)

重点类z
  • NSManagedObject

通过Core Data从数据库中取出的对象,默认情况下都是NSManagedObject对象.
NSManagedObject的工作模式有点类似于NSDictionary对象,通过键-值对来存取所有的实体属性.
setValue:forkey:存储属性值(属性名为key);
valueForKey:获取属性值(属性名为key). 每个NSManagedObject都知道自己属于哪个NSManagedObjectContext


  • NSManagedObjectContext:管理对象上下文

负责数据和应用库之间的交互(CRUD,即增删改查、保存等接口都在这个对象中).
所有的NSManagedObject都存在于NSManagedObjectContext中,所以对象和context是相关联的
每个 context 和其他 context 都是完全独立的
每个NSManagedObjectContext都知道自己管理着哪些NSManagedObject


  • NSManagedObjectModel:模型对象

Core Data的模型文件


  • NSPersistentStoreCoordinator:存储调度器

添加持久化存储库,CoreData的存储类型(比如SQLite数据库就是其中一种)
中间审查者,用来将对象图管理部分和持久化部分捆绑在一起,负责相互之间的交流(中介一样)


  • NSEntityDescription:

用来描述实体:相当于数据库表中一组数据描述

User中字段
@property (nonatomic) int16_t age;
@property (nonatomic) int64_t id;
@property (nullable, nonatomic, copy) NSString *name;
@property (nonatomic) BOOL sex;
复制代码
系统库
#import <CoreData/CoreData.h>
复制代码
打开数据库
// 创建数据库
    // 1. 实例化数据模型(将所有定义的模型都加载进来)
    // merge——合并
    self.managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
    
    // 2. 实例化持久化存储调度,要建立起桥梁,需要模型
    self.persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.managedObjectModel];
    
    // 3. 添加一个持久化的数据库到存储调度
    // 3.1 建立数据库保存在沙盒的URL
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSString *filePath = [[path stringByAppendingString:@"/"] stringByAppendingString:@"wudan.sqlite"];
    NSURL *pathUrl = [NSURL fileURLWithPath:filePath];
    
    // 3.2 打开或者新建数据库文件
    // 如果文件不存在,则新建之后打开
    // 否者直接打开数据库
    NSError *error;
    @try {
        [self.persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:pathUrl options:nil error:&error];
        self.context = [[NSManagedObjectContext alloc] init];
        self.context.persistentStoreCoordinator = self.persistentStoreCoordinator;
    } @catch (NSException *exception) {
        NSLog(@"Error:%@",error);
    } @finally {
        NSLog(@"打开数据库");
    }
复制代码
查询数据
  • 全部查询
- (void)queryAllResult:(void(^)(NSArray *dataArray))result {
    NSMutableArray *array = [NSMutableArray array];
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"id > 0"];
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"User"];
    request.predicate = predicate;
    NSError *error;
    
    NSArray *re = [self.context executeFetchRequest:request error:&error];
    if (re.count != 0) {
        for (User *user in re) {
            [array addObject:user];
        }
    }
    result(array);
}
复制代码
  • 分页查询
- (void)queryUserInfoWithPageNo:(NSInteger)pageNo pageSize:(NSInteger)pageSize result:(void(^)(NSArray *dataArray))result {
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"User"];
    NSSortDescriptor *scoreSort = [NSSortDescriptor sortDescriptorWithKey:@"id" ascending:true];
    request.sortDescriptors = @[scoreSort];
    request.fetchOffset = (pageNo - 1) * pageSize;
    request.fetchLimit = pageSize;
    
    NSError *error = nil;
    NSArray *re = [self.context executeFetchRequest:request error:&error];
    NSMutableArray *array = [NSMutableArray array];
    
    if (re.count != 0) {
        for (User *user in re) {
            [array addObject:user];
        }
    }
    result(array);
}
复制代码
  • 条件查询
- (void)queryUserInfoByObject:(id)object value:(id)value result:(void(^)(NSArray *dataArray))result  {
    NSMutableArray *array = [NSMutableArray array];
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ = '%@'", object, value]];
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"User"];
    request.predicate = predicate;
    NSError *error;
    
    NSArray *re = [self.context executeFetchRequest:request error:&error];
    if (re.count != 0) {
        for (User *user in re) {
            [array addObject:user];
        }
    }
    result(array);
}
复制代码
新增数据
- (void)addUserInfo:(NSInteger)userId name:(NSString *)name sex:(BOOL)sex age:(NSInteger)age success:(void(^)(void))success fail:(void(^)(void))fail {
    
    __block NSArray *array;
     [self queryUserInfoByObject:@"id" value:@(userId) result:^(NSArray * _Nonnull dataArray) {
         array = dataArray;
     }];
    
    if (array.count == 0) {
        
        User *user = [NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:self.context];
        user.name = name;
        user.id = userId;
        user.sex = sex;
        user.age = age;
        
        NSError *error;

        @try {
            [self.context save:&error];
            success();
        } @catch (NSException *exception) {
            NSLog(@"%@", error);
            fail();
        } @finally {
            NSLog(@"新增");
        }
    } else {
        fail();
    }
}
复制代码
更新数据
- (void)updateUserInfo:(NSInteger)userId infoDic:(NSDictionary *)dic success:(void(^)(void))success fail:(void(^)(void))fail {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"id = %ld", userId]];
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"User"];
    request.predicate = predicate;
    NSError *error;
    
    if (dic.count > 0) {
        NSArray *re = [self.context executeFetchRequest:request error:&error];
        if (re.count > 0) {
            for (User *user in re) {
                [dic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
                    [user setValue:obj forKey:key];
                }];
            }
        }
        
        @try {
            [self.context save:&error];
            success();
        } @catch (NSException *exception) {
            NSLog(@"%@", error);
            fail();
        } @finally {
            NSLog(@"更新");
        }
    }
}
复制代码
删除数据
- (void)deleteUserInfo:(NSInteger)userId success:(void(^)(void))success fail:(void(^)(void))fail {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"id = %ld", userId]];
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"User"];
    request.predicate = predicate;
    NSError *error;
    
    NSArray *re = [self.context executeFetchRequest:request error:&error];
    if (re.count > 0) {
        @try {
            [self.context deleteObject:re.firstObject];
            [self.context save:nil];
            success();
        } @catch (NSException *exception) {
            NSLog(@"%@", error);
            fail();
        } @finally {
            NSLog(@"删除数据");
        }
    } else {
        NSLog(@"数据库中暂无该数据");
        fail();
    }
}
复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值