学习CoreData之前需要搞清楚的几个名词:
1、NSManagedObjectContext 管理对象,上下文,持久性存储模型对象
2、NSManagedObjectModel 被管理的数据模型,数据结构
3、NSPersistentStoreCoordinator 连接数据库的
4、NSManagedObject 被管理的数据记录
5、NSFetchRequest 数据请求
6、NSEntityDescription 表格实体结构
此外还需要知道.xcdatamodel文件编译后为.momd或者.mom文件
如果你在新建工程的时候,勾选了“引用CoreData”,那么在新建完成的工程的Appdelegate文件中就会看到NSManagedObjectContext等CoreData的相关声明;如果没有的话就需要自己去添加这一部分代码,下面是一个小封装:
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@interface CoreDataManager : NSObject
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;
//插入数据
- (void)insertCoreData:(NSMutableArray*)dataArray;
//查询
- (NSMutableArray*)selectData:(int)pageSize andOffset:(int)currentPage;
//删除
- (void)deleteData;
//更新
- (void)updateData:(NSString*)userName withCardId:(NSString*)cardId;
@end
#import "CoreDataManager.h"
#import "Student.h"
@implementation CoreDataManager
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
- (NSURL *)applicationDocumentsDirectory {
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
- (NSManagedObjectModel *)managedObjectModel {
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"DKFoundation" 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:@"DKFoundation.sqlite"];
NSError * error;
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;
}
#pragma mark - Core Data Saving support
- (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();
}
}
}
//插入数据
- (void)insertCoreData:(NSMutableArray*)dataArray{
NSManagedObjectContext * context = [self managedObjectContext];
for(Student * stu in dataArray){
Student *student = [NSEntityDescription insertNewObjectForEntityForName:@"Student"
inManagedObjectContext:context];
student.userName = stu.userName;
student.cardId = stu.cardId;
NSError * error;
if([context save:&error]){
NSLog(@"保存成功");
}else{
NSLog(@"保存失败,报错信息如下:%@",error);
}
}
}
//查询
- (NSMutableArray *)selectData:(int)pageSize andOffset:(int)currentPage{
NSManagedObjectContext *context = [self managedObjectContext];
// 限定查询结果的数量
//setFetchLimit
// 查询的偏移量
//setFetchOffset
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setFetchLimit:pageSize];
[fetchRequest setFetchOffset:currentPage];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSError *error;
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
NSMutableArray *resultArray = [NSMutableArray array];
for (Student *stu in fetchedObjects) {
[resultArray addObject:stu];
}
return resultArray;
}
//删除
- (void)deleteData{
NSManagedObjectContext *context = [self managedObjectContext];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setIncludesPropertyValues:NO];
[request setEntity:entity];
NSError *error = nil;
NSArray *datas = [context executeFetchRequest:request error:&error];
if (!error && datas && [datas count])
{
for (NSManagedObject *obj in datas)
{
[context deleteObject:obj];
}
if (![context save:&error])
{
NSLog(@"error:%@",error);
}
}
}
//更新
- (void)updateData:(NSString*)userName withCardId:(NSString*)cardId{
NSManagedObjectContext *context = [self managedObjectContext];
NSPredicate *predicate = [NSPredicate
predicateWithFormat:@"userName like[cd] %@",userName];
//首先你需要建立一个request
NSFetchRequest * request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Student" inManagedObjectContext:context]];
[request setPredicate:predicate];//这里相当于sqlite中的查询条件,具体格式参考苹果文档
NSError *error = nil;
NSArray *result = [context executeFetchRequest:request error:&error];
for (Student *stu in result) {
stu.cardId = [NSNumber numberWithInt:[cardId intValue]];
}
//保存
if ([context save:&error]) {
//更新成功
NSLog(@"更新成功");
}
}
@end