美文网首页
CoreData基础

CoreData基础

作者: demoker | 来源:发表于2015-08-21 15:26 被阅读232次

学习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

相关文章

  • 第五篇:CoreData

    CoreData 初识CoreData 基础使用CoreData 高级使用CoreData 使用进阶CoreDat...

  • iOS_DataBase

    相关实用连接1.认识CoreData - 初识CoreData2.认识CoreData - 基础使用3.iOS进阶...

  • [swift]swift4.0 CoreData的使用

    CoreData基础在CoreData中有一些常用的类,称呼可能各不相同。NSPersistentStoreCoo...

  • CoreData基础

    学习CoreData之前需要搞清楚的几个名词: 1、NSManagedObjectContext 管理对象,...

  • CoreData基础用法

    一、简单介绍Core Data是iOS5之后才出现的一个框架,它提供了对象-关系映射(ORM)的功能,即能够将OC...

  • CoreData在swift/oc中简单应用

    基础的,增、删、改、查。demo地址https://github.com/wl199452/coreData-

  • CoreData+多线程

    基础知识:Core Data入门 查询语句:[IOS开发]CoreData条件查询之NSPredicate应用_超...

  • CoreData-基础使用

    CoreData的优势: 1.CoreData可以实现对xml,二进制文件,sql数据文件的访问 2.可以节省代码...

  • CoreData基础教程

    使用CoreData来保存数据 1.创建DataModel,创建Entity,添加属性,创建NSManagedOb...

  • iOS基础--CoreData 总结

    CoreData 数据持久化框架是Cocoa API的一部分,它允许按照 实体-属性-值 模型组织数据,并以XML...

网友评论

      本文标题:CoreData基础

      本文链接:https://www.haomeiwen.com/subject/wlmiqttx.html