1.Core Data 是数据持久化的一种方式
2.数据最终的存储类型可以是以下几种:
3.好处:能够合理管理内存,避免使用sql的麻烦,高效
4.构成:
(1)NSManagedObjectContext(被管理的数据上下文)
操作实际内容(操作持久层)
作用:插入数据,查询数据,删除数据
(2)NSManagedObjectModel(被管理的数据模型)
作用:添加实体的属性,建立属性之间的关系
操作方法:视图编辑器,或代码
(3)NSPersistentStoreCoordinator(持久化存储助理)
作用:设置数据存储的名字,位置,存储方式,和存储时机
(4)NSManagedObject(被管理的数据记录)
(5)NSFetchRequest(获取数据的请求)
(6)NSEntityDescription(实体结构)
(7)后缀为.xcdatamodeld的包
里面是.xcdatamodel文件,用数据模型编辑器编辑
编译后为.momd或.mom文件
5.依赖关系
二、创建Core Data
1、新建一个工程,在设置好工程名和其他设置后勾选上user Core Data
2、工程创建好之后可以看到AppDelegate.h中自动生成了Core Data相关属性和方法
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;//上下文属性
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;//model对象属性
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void)saveContext;//保存数据到持久层
- (NSURL *)applicationDocumentsDirectory;//沙盒目录下的路径
3、在 AppDelegate.m中
3.1 自动生成
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
3.2 Documents路径
- (NSURL *)applicationDocumentsDirectory {
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
- (NSManagedObjectModel *)managedObjectModel {
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Core_Data" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Core_Data.sqlite"];
NSError *error = nil;
NSString *failureReason = @"There was an error creating or loading the application's saved data.";
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
dict[NSLocalizedFailureReasonErrorKey] = failureReason;
dict[NSUnderlyingErrorKey] = error;
error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
- (NSManagedObjectContext *)managedObjectContext {
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (!coordinator) {
return nil;
}
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
return _managedObjectContext;
}
3.7 保存数据到持久层
- (void)saveContext {
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
NSError *error = nil;
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
}
4、在
4.1 点击添加实体
4.2 添加实体和实体属性
4.3 再添加一个实体,让两个实体关联上
5、导出Message和UserInfo两个实体
第一步
5.2
第二步
第三步
导出之后可以看到工程目录下多了两个类
1、UserInfo.h
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@class Message;
@interface UserInfo : NSManagedObject
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSNumber * age;
@property (nonatomic, retain) NSData * headImage;
@property (nonatomic, retain) Message *message;
@end
UserInfo.m
#import "UserInfo.h"
#import "Message.h"
@implementation UserInfo
@dynamic name;
@dynamic age;
@dynamic headImage;
@dynamic message;
@end
2、Message.h
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@interface Message : NSManagedObject
@property (nonatomic, retain) NSString * title;
@property (nonatomic, retain) NSString * content;
@end
Message.m
#import "Message.h"
@implementation Message
@dynamic title;
@dynamic content;
@end
6、存储数据
6.1、在AppDelegate.h中声明一个工厂方法
+ (AppDelegate *)appDelegate;
在
AppDelegate.m中实现
+ (AppDelegate *)appDelegate{
return (AppDelegate *)[UIApplication sharedApplication].delegate;
}
6.2、 操作coreData
1、不管增删改查都需要先初始化上下文[app managedObjectContext]
2、插入具体内容到上下文
+ (id)insertNewObjectForEntityForName:(NSString *)entityName inManagedObjectContext:(NSManagedObjectContext *)context;
3、保存 saveContext
//1、初始化上下文
NSManagedObjectContext *context = [[AppDelegate appDelegate] managedObjectContext];
//2、插入具体内容到上下文
//实体描述
Message *message = [NSEntityDescription insertNewObjectForEntityForName:@"Message" inManagedObjectContext:context];
NSArray *textArray = @[@"不管增删改查都需要先初始化", @"插入具体内容到上下文", @"Core Data"];
int textArc = arc4random()%textArray.count;
[message setValue:textArray[textArc] forKey:@"title"];
[message setValue:textArray[textArc] forKey:@"content"];
NSArray *images = @[@"bg", @"start", @"Default"];
int arc = arc4random()%images.count;
UserInfo *userInfo = [NSEntityDescription insertNewObjectForEntityForName:@"UserInfo" inManagedObjectContext:context];
[userInfo setValue:images[arc] forKey:@"name"];
[userInfo setValue:@(20 + arc) forKey:@"age"];
UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%@", images[arc]]];
[userInfo setValue:UIImagePNGRepresentation(image) forKey:@"headImage"];
[userInfo setValue:message forKey:@"message"];
//3、保存数据
[[AppDelegate appDelegate] saveContext];
7、查找数据
读取coreData步骤
0、初始化上下文 managedObjectContext
1、读取managedObjectModel
2、找到里面所有实体的名字[model entitiesByName]
3、找到要读取的实体NSEntityDescription *entry = entryDic[@"UserInfo"];
4、初始化查询对象 NSFetchRequest *request = [[NSFetchRequest alloc]init];
5、通过上下文 查找 NSArray *list = [context executeFetchRequest:request error:nil];
//0、初始化上下文
NSManagedObjectContext *centext =[[AppDelegate appDelegate] managedObjectContext];
//1、读取managedObjectModel
NSManagedObjectModel *model = [[AppDelegate appDelegate] managedObjectModel];
//2、找到里面所有实体的名字[model entitiesByName]
NSDictionary *entryDic = [model entitiesByName];
//3、找到要读取的实体
NSEntityDescription *entry = entryDic[@"UserInfo"];
//4、初始化查询请求对象 NSFetchRequest
NSFetchRequest *request = [[NSFetchRequest alloc] init];
request.entity = entry;
//request.predicate 谓词查询
//request.fetchLimit 分页查询
//request.fetchOffset 偏移量
//5、通过上下文查找
//初始化一个数组用于接收
dataList = [NSArray array];
<p style="margin-top: 0px; margin-bottom: 0px; font-family: Menlo;"><span style="font-size: 14px;"> </span><span style="font-size:10px;">if (dataList.count != 0) {</span></p><p style="margin-top: 0px; margin-bottom: 0px; font-family: Menlo; min-height: 16px;"><span style="font-size:10px;"> [showTableView reloadData];</span></p><p style="margin-top: 0px; margin-bottom: 0px; font-family: Menlo;"><span style="font-size:10px;"> }</span></p>
8、在ViewController中初始化一个UITableView用于数据展示
8.1 初始化表视图
showTableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
showTableView.delegate = self;
showTableView.dataSource = self;
showTableView.rowHeight = 100;
[self.view addSubview:showTableView];
8.2 tableView delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return dataList.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *showCellID = @"showCellID";
UITableViewCell *showCell = [tableView dequeueReusableCellWithIdentifier:showCellID];
if (!showCell) {
showCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:showCellID];
}
UserInfo *info = dataList[indexPath.row];
showCell.imageView.image = [UIImage imageWithData:info.headImage];
showCell.textLabel.text = info.name;
Message *message = info.message;
showCell.detailTextLabel.text = message.title;
return showCell;
}
最终效果图