iOS App中数据管理框架Core Data的基本数据操作教程

2020-01-15 15:20:58王旭

    SchoolClass * modelS = [NSEntityDescription insertNewObjectForEntityForName:@"SchoolClass" inManagedObjectContext:moc];
    //对数据进行设置
    modelS.name = @"第一班";
    modelS.stuNum = @60;
    //进行存储
    if ([moc save:nil]) {
        NSLog(@"新增成功");
    }
    NSLog(@"%@",[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"CoreDataExample.sqlite"]);
找到在打印出的路径,会发现里面多了一个sqlite文件,其中有一张表中添加进了一条数据。

二、查询数据

CoreData中通过查询请求来对数据进行查询操作,查询请求由NSFetchRequest来进行管理和维护。

NSFetchRequest主要提供两个方面的查询服务:

1.提供范围查询的相关功能

2.提供查询结果返回类型与排序的相关功能

NSFetchRequest中常用方法如下:

//创建一个实体的查询请求 可以理解为在某个表中进行查询
+ (instancetype)fetchRequestWithEntityName:(NSString*)entityName;
//查询条件
@property (nullable, nonatomic, strong) NSPredicate *predicate;
//数据排序
@property (nullable, nonatomic, strong) NSArray<NSSortDescriptor *> *sortDescriptors;
//每次查询返回的数据条数
@property (nonatomic) NSUInteger fetchLimit;
//设置查询到数据的返回类型
/*
typedef NS_OPTIONS(NSUInteger, NSFetchRequestResultType) {
    NSManagedObjectResultType  = 0x00,
    NSManagedObjectIDResultType  = 0x01,
    NSDictionaryResultType          NS_ENUM_AVAILABLE(10_6,3_0) = 0x02,
    NSCountResultType    NS_ENUM_AVAILABLE(10_6,3_0) = 0x04
};
*/
@property (nonatomic) NSFetchRequestResultType resultType;
//设置查询结果是否包含子实体
@property (nonatomic) BOOL includesSubentities;
//设置要查询的属性值
@property (nullable, nonatomic, copy) NSArray *propertiesToFetch;
在SchoolClass实体中查询数据,使用如下的代码:

    //创建一条查询请求
    NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName:@"SchoolClass"];
    //设置条件为 stuNum=60的数据
    [request setPredicate:[NSPredicate predicateWithFormat:@"stuNum == 60"]];
    //进行查询操作
    NSArray * res = [moc executeFetchRequest:request error:nil];