1、笔者认为core data就是ios内置的一个操作sqlite的框架。
a、首先了解Core data的基本信息
在使用代码操作coredata框架前,先了解core data中的几个重要对象和重要操作
操作:
a、添加CoreData框架
b、导入#import<CoreData/CoreData.h>
对象:
1、NSManagedObjectContext 管理对象,上下文,持久性存储模型对象
2、NSManagedObjectModel 被管理的数据模型,[数据结构](http://lib.csdn.net/base/31)
3、NSPersistentStoreCoordinator 连接数据库的
4、NSManagedObject 被管理的数据记录
5、NSFetchRequest 数据请求
6、NSEntityDescription 表格实体结构
注意:
tip1:需要知道.xcdatamodel文件编译后为.momd或者.mom文件。
tip2:core data的数据文件生成在沙盒的document文件夹下面。
b、使用core data的个人琢磨步骤
tip1:创建《Data Model》文件(Animations)。
tip2:在Animations中创建一个实体(表)Animate。
tip3:创建《NSManagedObject subclass》文件,生成Animate的属性文件AnimateEntity。
tip4:编写操纵core data框架的oc代码,即entity的管理文件AnimateEntityManager。
下面贴出,笔者实现AnimateEntityManager的代码
#import <Foundation/Foundation.h>
#import "AnimateEntity.h"
@interface AnimateEntityManager : 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*)newsId withIsLook:(NSString*)islook;
@end
#import "AnimateEntityManager.h"
@import CoreData;
#define TableName @"AnimateEntity"
@implementation AnimateEntityManager
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
- (void)saveContext
{
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
}
#pragma mark - Core Data stack
// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
- (NSManagedObjectContext *)managedObjectContext
{
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return _managedObjectContext;
}
// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
- (NSManagedObjectModel *)managedObjectModel
{
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Animations" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Animations.sqlite"];
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
#pragma mark - Application's Documents directory
// Returns the URL to the application's Documents directory.获取Documents路径
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
//插入数据
- (void)insertCoreData:(NSMutableArray*)dataArray
{
// NSLog(@"%@",NSHomeDirectory());
NSManagedObjectContext *context = [self managedObjectContext];
for (AnimateEntity *entity in dataArray) {
AnimateEntity *entityInfo = [NSEntityDescription insertNewObjectForEntityForName:TableName inManagedObjectContext:context];
entityInfo.term = entity.term;
entityInfo.termUnit = entity.termUnit;
NSError *error;
if(![context save:&error])
{
NSLog(@"不能保存:%@",[error localizedDescription]);
}
}
}
//查询
- (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:TableName inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSError *error;
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
NSMutableArray *resultArray = [NSMutableArray array];
for (AnimateEntity *info in fetchedObjects) {
NSLog(@"interestBearingtime:%@", info.interestBearingtime);
NSLog(@"projectName:%@", info.projectName);
[resultArray addObject:info];
}
return resultArray;
}
//删除
-(void)deleteData
{
NSManagedObjectContext *context = [self managedObjectContext];
NSEntityDescription *entity = [NSEntityDescription entityForName:TableName 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*)newsId withIsLook:(NSString*)repaymentMethoud
{
NSManagedObjectContext *context = [self managedObjectContext];
NSPredicate *predicate = [NSPredicate
predicateWithFormat:@"newsid like[cd] %@",newsId];
//首先你需要建立一个request
NSFetchRequest * request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:TableName inManagedObjectContext:context]];
[request setPredicate:predicate];//这里相当于sqlite中的查询条件,具体格式参考苹果文档
//https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Predicates/Articles/pCreating.html
NSError *error = nil;
NSArray *result = [context executeFetchRequest:request error:&error];//这里获取到的是一个数组,你需要取出你要更新的那个obj
for (AnimateEntity *info in result) {
info.repaymentMethoud = repaymentMethoud;
}
//保存
if ([context save:&error]) {
//更新成功
NSLog(@"更新成功");
}
}
@end
网友评论