前几天项目里面加入了CoreData,第一次用,记录一下,这里只记录创建项目之后添加的CoreData。
demo地址: CoreDataDemo
1. 创建CoreData模型文件
2. 创建项目中需要用到的实体(Entities),这里已person为例,创建一个Person实体(类)
3. 修改刚创建的实体类名字,并添加属性
4. 设置CoreData模型文件
5.生成实体的模型文件
6. 到此实体类创建完成,但真正使用时候还要生成上下文关联文件,我直接封装成了单例方便使用
a. 创建单例文件 PersonManager
b. 引入头文件、实例化、写单例,
.h
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#import "Person+CoreDataClass.h"
@interface PersonManager : NSObject
@property (strong, nonatomic) NSManagedObjectContext *context;
@property (strong, nonatomic) NSFetchRequest *request;
+ (instancetype)shareManager;
.m
#import "PersonManager.h"
@implementation PersonManager
static PersonManager *personManager;
+ (instancetype)shareManager {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
personManager =[[self alloc] init];
});
return personManager;
}
- (instancetype)init {
if (self =[super init]) {
}
return self;
}
c. 生成CoreData上下文关联文件
//1、创建模型对象获、取模型路径
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"PersonData" withExtension:@"momd"];
//根据模型文件创建模型对象
NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
//2、创建持久化助理、利用模型对象创建助理对象
NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
//数据库的名称和路径
NSString *docStr = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *sqlPath = [docStr stringByAppendingPathComponent:@"coreData.sqlite"];
NSLog(@"path = %@", sqlPath);
NSURL *sqlUrl = [NSURL fileURLWithPath:sqlPath];
//设置数据库相关信息
[store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:sqlUrl options:nil error:nil];
//3、创建上下文
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
//关联持久化助理
[context setPersistentStoreCoordinator:store];
self.context = context;
self.request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
7. 到此关联完成,单例创建完成,继续在单例中进行封装: 增、删、改、查
- 读取全部CoreData中数据,读取出来的是转换好的Person模型
- (NSArray <Person *>*)readAllData {
// 检索条件制空就是搜索全部
self.request.predicate = nil;
return [self.context executeFetchRequest:self.request error:nil];
}
- 插入数据,添加数据
- (BOOL)insertDataWithPersonID:(NSString *)personID name:(NSString *)name age:(int16_t)age photo:(NSString *)photo {
Person * person =[NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.context];
person.personID =personID;
person.name =name;
person.age =age;
person.photo =photo;
NSError *error = nil;
if ([self.context save:&error]) {
return YES;
}
return NO;
}
- 删除数据
- (BOOL)deleteDataWithPersonID:(NSString *)personID {
//删除条件
NSPredicate *pre = [NSPredicate predicateWithFormat:@"personID = %@",personID];
self.request.predicate = pre;
//返回需要删除的对象数组
NSArray *deleArray = [_context executeFetchRequest:self.request error:nil];
//从数据库中删除
for (Person *person in deleArray) {
[self.context deleteObject:person];
}
NSError *error = nil;
if ([self.context save:&error]) {
return YES;
}
return NO;
}
- 修改数据、更新数据
// 这里dict中的key与value要与person中属性和名字都相同
- (BOOL)upDateDataWithPersonID:(NSString *)personID dict:(NSDictionary *)updateDict {
NSPredicate *pre = [NSPredicate predicateWithFormat:@"personID = %@",personID];
self.request.predicate = pre;
NSArray *resArray = [self.context executeFetchRequest:self.request error:nil];
for (Person *person in resArray) {
for (NSString *key in [updateDict allKeys]) {
[person setValue:updateDict[key] forKey:key];
}
}
NSError *error = nil;
if ([self.context save:&error]) {
return YES;
}
return NO;
}
- 查找数据
- (Person *)searchDataWithPersonID:(NSString *)personID {
//查询条件
NSPredicate *pre = [NSPredicate predicateWithFormat:@"personID = %@",personID];
self.request.predicate = pre;
//发送查询请求,并返回结果
NSArray *resArray = [self.context executeFetchRequest:self.request error:nil];
if (resArray.count>0) {
return [resArray firstObject];
}
return nil;
}
8. 增删改查基本操作已经封装好,接下来就是使用了,用法也比较简单
简单写了一个tableView,具体代码就不写了,写几个查询方法吧,
// 读取全部写入数组中
[self.dataSource addObjectsFromArray:[[PersonManager shareManager] readAllData]];
// 插入数据到数据库中
[[PersonManager shareManager] insertDataWithPersonID:[NSString stringWithFormat:@"%d",personId]
name:[NSString stringWithFormat:@"客服%02d",personId]
age:arc4random()%20
photo:@"photo"];
// 从数据库中查询
[self.dataSource addObject:[[PersonManager shareManager] searchDataWithPersonID:[NSString stringWithFormat:@"%d",personId]]];
// 删除数据
[[PersonManager shareManager] deleteDataWithPersonID:person.personID];
网友评论