Apple官方文档介绍:
Core Data
Persist or cache data and support undo on a single device.
Overview
Use Core Data to save your application’s permanent data for offline use, to cache temporary data, and to add undo functionality to your app on a single device.
Through Core Data’s Data Model editor, you define your data’s types and relationships, and generate respective class definitions. Core Data can then manage object instances at runtime to provide the following features.
Persistence
Core Data abstracts the details of mapping your objects to a store, making it easy to save data from Swift and Objective-C without administering a database directly.
Undo and Redo of Individual or Batched Changes
Core Data’s undo manager tracks changes and can roll them back individually, in groups, or all at once, making it easy to add undo and redo support to your app.
Background Data Tasks
Perform potentially UI-blocking data tasks, like parsing JSON into objects, in the background. You can then cache or store the results to reduce server roundtrips.
View Synchronization
Core Data also helps keep your views and data synchronized by providing data sources for table and collection views.
Versioning and Migration
Core Data includes mechanisms for versioning your data model and migrating user data as your app evolves.
CoreData使用简章:
一、在新项目中添加CoreData
方式一:新建项目工程时,勾选上Use Core Data复选框
方式二:Command+N新建文件,选择Core Data栏目下的Data Model文件,按步骤完成数据库文件的创建
二、创建数据库文件后,给数据库添加实体模型,添加模型会自动生成Configurations配置信息,后面根据配置信息来创建数据库模型类文件
三、创建模型后,根据需求给模型添加属性
四、添加模型属性后,创建模型类
方式一:Edit0r->Create NSManagedObject Subclass...,自动生成步骤二命名的模型类,创建前要选择好语言环境OC/Swift
Create NSManagedObject Subclass...,按照步骤完成创建
方式二:Command+N创建继承自NSManagedObject的模型类,命名为步骤二添加模型的名称,在.h文件申明模型各属性信息,.m文件中@dynamic修饰各属性。
.h文件
#import <CoreData/CoreData.h>
NS_ASSUME_NONNULL_BEGIN
@interface MyModel : NSManagedObject
@property (nonatomic) int16_t age;
@property (nullable, nonatomic, copy) NSString *name;
@property (nonatomic) BOOL sex;
@property (nullable, nonatomic, copy) NSDate *birthday;
+ (NSFetchRequest<MyModel *> *)fetchRequest;
@end
NS_ASSUME_NONNULL_END
.m文件
#import "MyModel.h"
@implementation MyModel
@dynamic age;
@dynamic name;
@dynamic sex;
@dynamic birthday;
+ (NSFetchRequest<MyModel *> *)fetchRequest {
return [NSFetchRequest fetchRequestWithEntityName:@"MyModel"];
}
@end
五、对数据库进行操作(增、删、改、查)
1.Reference库及模型类Header文件,申明持久化容器全局变量,初始化持久化容器NSPersistentContainer(懒加载)
#import "ViewController.h"
#import <CoreData/CoreData.h>
#import "MyModel.h"
@interface ViewController ()
@property (strong, nonatomic) NSPersistentContainer *container;
@end
//懒加载
- (NSPersistentContainer *)container {
if(!_container) {
//根据数据库文件初始化容器
_container = [[NSPersistentContainer alloc] initWithName:@"MyCoreData"];
//Load stores from the storeDescriptions property that have not already been successfully added to the container. The completion handler is called once for each store that succeeds or fails.
// 从尚未成功添加到容器中的Store Description属性加载存储。 对于成功或失败的每个存储,调用一次完成处理程序。
/** 加载数据库基本信息(必须调用)
* NSManagedObjectContext 管理上下文
* NSPersistentStoreCoordinator 持久化存储协调器(助手)
* NSPersistentStore 持久化存储对象(特殊)
* NSEntityDescription 实体结构(表结构)
*/
[_container loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription * _Nonnull storeDescription, NSError * _Nullable error) {
//code area
}];
}
return _container;
}
2.增操作(inset into **** (name, age, sex, birthday) values ('****', 18, 1, ****);)
//执行后台操作任务
[self.container performBackgroundTask:^(NSManagedObjectContext * _Nonnull context) {
[context performBlockAndWait:^{
//创建一个空的数据模拟对象
MyModel *model = [NSEntityDescription insertNewObjectForEntityForName:@"MyModel" inManagedObjectContext:context];
model.name=@"张三";
model.birthday= [NSDatedate];
model.age=12;
model.sex=YES;
//插入上面的数据
NSError *error =nil;
[context save:&error];
if(error) {
NSLog(@"插入失败: %@", error.userInfo);
}else{
NSLog(@"插入成功");
}
}];
}];
3.查操作(select * from **** where name='张三' order by age asc;)
//select * from ****;
//select * from **** where name='张三';
//select * from **** where name='张三' order by age asc;
[self.container performBackgroundTask:^(NSManagedObjectContext * _Nonnull context) {
NSFetchRequest *request = [MyModel fetchRequest];
//添加附加条件的查询(sqlite语句)
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@ OR age=%d", @"张三",12];
request.predicate= predicate;
//添加排序的条件
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];
request.sortDescriptors=@[sort];
NSError *error =nil;
NSArray *resultArray = [context executeFetchRequest:request error:&error];
if(error) {
NSLog(@"查询失败:%@", error.userInfo);
}
for(MyModel *model in resultArray) {
NSLog(@"名字:%@; 年龄:%d; 性别:%@", model.name,model.age, model.sex?@"男":@"女");
}
}];
4.删操作(delete from **** where name='****';)
//delete from **** where name='张三'
[self.container performBackgroundTask:^(NSManagedObjectContext * _Nonnull context) {
NSFetchRequest*request = [MyModelfetchRequest];
//添加附加条件的查询
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@", @"张三"];
request.predicate= predicate;
//获取所有名字叫“张三”的记录
NSError *error =nil;
NSArray *resultArray = [context executeFetchRequest:request error:&error];
if(error) {
NSLog(@"查询失败");
}
//删除查询后的所有记录
for(MyModel *model in resultArray) {
//将上面的记录从数据库中删除(**从内存中删除对象)
[context deleteObject:model];
}
//执行保存操作(真正的从数据库中删除)
[context save:&error];
if(error) {
NSLog(@"删除失败: %@", error.userInfo);
}else{
NSLog(@"删除成功");
}
}];
5.改操作(update **** set name='****' where name='****';)
[self.container performBackgroundTask:^(NSManagedObjectContext * _Nonnull context) {
NSFetchRequest *request = [MyModel fetchRequest];
//添加附加条件的查询
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@", @"张三"];
request.predicate= predicate;
//获取查询的结果(名字叫做“张三”的所有记录)
NSError *error =nil;
NSArray *resultArray = [context executeFetchRequest:request error:&error];
if(error) {
NSLog(@"查询失败:%@", error.userInfo);
}
//循环修改查询后的数据
for(MyModel *model in resultArray) {
model.name=@"李四";
}
//写到数据库中
[context save:&error];
if(error) {
NSLog(@"更新失败:%@", error.userInfo);
}else{
NSLog(@"更新成功");
}
}];
以上只为CoreData的简单使用,后面还会添加Relationship等的使用简章
▶︎欢迎查阅