Core Data初始
Core Data 是 iOS系统提供的数据存储方式,和传统的SQL相比:
- 它无需写SQL语句
- 允许开发者用面向对象的方式操作存储数据,它的实体类可以和table中的表结构对应
- 可以通过谓词指定查询条件
- 由于是苹果的亲儿子,在iOS系统上的性能很好,苹果也对它进行了多次优化
- 苹果官方应用的数据存储几乎都使用 Core Data
Core Data 原理
CoreData的核心是Core Data stack(技术栈堆)。CoreData就是依靠Core Data stack中的几个对象进行数据操作的。
关系图NSManagedObjectContext ,管理对象的上下文: 负责管理模型对象的一个集合,
NSManagedObjectModel 被管理的对象模型
NSPersistentStoreCoordinator 存储调度器: 负责将数据保存到磁盘,
NSPersistentStore用于保存模型数据,受NSPersistentStoreCoordinator 存储调度器的操控。
Core Data 使用
1.创建数据库文件
可以创建工程时勾选“use core data”,如果工程已经创建,也可以新创建一个数据库文件
新建数据库文件
2.创建数据模型
创建数据模型3.生成代码文件
生成代码文件这就生成后的类
生成的类.png
4.创建一个管理类
#import "NCModel.h"
#import <CoreData/CoreData.h>
#define kNCHandleCoreDataModelInstance [NCHandleCoreDataModel shareInstance]
NS_ASSUME_NONNULL_BEGIN
@interface NCHandleCoreDataModel : NCModel
+(NCHandleCoreDataModel *)shareInstance;
@property(strong,nonatomic)NSManagedObjectContext *managerContenxt;
@property(strong,nonatomic)NSManagedObjectModel *managerModel;//模型对象
@property(strong,nonatomic)NSPersistentStoreCoordinator *maagerDinator; //存储调度器
-(void)save;
@end
#import "NCHandleCoreDataModel.h"
@implementation NCHandleCoreDataModel
+ (NCHandleCoreDataModel *)shareInstance
{
static NCHandleCoreDataModel *instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[NCHandleCoreDataModel alloc]init];
});
return instance;
}
- (NSURL*)getDocumentUrlPath
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]
;
}
-(NSManagedObjectContext *)managerContenxt
{
if (_managerContenxt != nil) {
return _managerContenxt;
}
_managerContenxt = [[NSManagedObjectContext alloc]initWithConcurrencyType:NSMainQueueConcurrencyType];
[_managerContenxt setPersistentStoreCoordinator:self.maagerDinator];
return _managerContenxt;
}
-(NSManagedObjectModel *)managerModel
{
if (_managerModel != nil) {
return _managerModel;
}
_managerModel = [NSManagedObjectModel mergedModelFromBundles:nil];
return _managerModel;
}
-(NSPersistentStoreCoordinator *)maagerDinator
{
if (_maagerDinator != nil) {
return _maagerDinator;
}
_maagerDinator = [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:self.managerModel];
NSURL *url = [[self getDocumentUrlPath]URLByAppendingPathComponent:@"nicolsDatabase.db" isDirectory:YES];
[_maagerDinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:nil];
return _maagerDinator;
}
-(void)save
{
[self.managerContenxt save:nil];
}
@end
封装的是一个单例类,创建一个单例,然后懒加载一个NSManagedObjectContext,并给NSManagedObjectContext添加存储调度器NSPersistentStoreCoordinator。懒加载存储调度器的时候给存储调度器添加存储器PersistentStore。在最后提供一个保存数据的方法,每次我们修改数据库中文件数据的时候,都需要用Core Data stack调用save方法保存数据。
core 的增删改查
//增
Student *s = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:kNCHandleCoreDataModelInstance.managerContenxt];
s.s_id = 12;
s.s_name = @"尼古";
s.s_age = 26;
s.s_sex = 1;
[kNCHandleCoreDataModelInstance save];
//查
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Student"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"s_name == %@",@"尼古"];
request.predicate = predicate;
NSArray<Student*> *arr = [kNCHandleCoreDataModelInstance.managerContenxt executeFetchRequest:request error:nil];
//改
arr.firstObject.s_name = @"尼古新";
arr.firstObject.s_age = 25;
[kNCHandleCoreDataModelInstance save];
//删
[kNCHandleCoreDataModelInstance.managerContenxt deleteObject:arr.firstObject];
[kNCHandleCoreDataModelInstance save];
第三方框架MagicalRecord的使用
使用MagicalRecord可以避免了写很多配置,只需要几行代码就能够完成项目的需求。
下载MagicalRecord,将MagicalRecord文件夹导入到工程中。
1.初始化数据库
在- (BOOL)application:(UIApplication)application didFinishLaunchingWithOptions:(NSDictionary)launchOptions 添加如下代码,你也可以封装一个专门的类
- (void)initMagicalrecord{
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
path = [path stringByAppendingPathComponent:@"nicolas.sqlite"];
NSURL *url = [NSURL fileURLWithPath:path];
[MagicalRecord setLoggingLevel:MagicalRecordLoggingLevelWarn];
[MagicalRecord setupCoreDataStackWithStoreAtURL:url];
}
2.增删改查
//增
for (NSInteger i = 0; i < 10; i ++) {
Student *student = [Student MR_createEntity];
student.s_id = i;
student.s_name = [@"小名" stringByAppendingString:@(i).stringValue];
student.s_age = arc4random() % 6 +10;
student.s_sex = arc4random() % 2;
}
for (NSInteger i = 0; i < 10; i ++) {
Teacher *teacher = [Teacher MR_createEntity];
teacher.t_id = i;
teacher.t_name = [@"张老师" stringByAppendingString:@(i).stringValue];
teacher.t_sex = arc4random() % 2;
}
//查
NSArray *allStudent = [Student MR_findAll];
for (Student *s in allStudent) {
NSLog(@"===1=Student=s_id:%ld=s_name:%@=s_age:%ld=s_sex:%ld",s.s_id,s.s_name,s.s_age,s.s_sex);
}
NSArray *teacherArr = [Teacher MR_findByAttribute:@"t_sex" withValue:@(0)];
NSLog(@"===2==%@",teacherArr);
//删
for (Teacher *t in teacherArr) {
[t MR_deleteEntity];
}
[[NSManagedObjectContext MR_defaultContext] MR_saveOnlySelfAndWait];
//改
NSArray *student = [Student MR_findByAttribute:@"s_age" withValue:@(12)];
for (Student *s in student) {
s.s_name = @"小屁孩";
}
[[NSManagedObjectContext MR_defaultContext] MR_saveOnlySelfAndWait];
NSArray *allStu = [Student MR_findAll];
for (Student *s in allStu) {
NSLog(@"===2=Student=s_id:%ld=s_name:%@=s_age:%ld=s_sex:%ld",s.s_id,s.s_name,s.s_age,s.s_sex);
}
数据库查看工具:http://sqlitebrowser.org/
最后留下 Demo地址 .
写的有些仓促,文章和代码若有不对地方,欢迎批评指正。
网友评论