CoreData使用
//NoteManagedObject.h
//NoteCoreDataLearn
//
//Created by ChengDavid on 14-7-6.
//Copyright (c) 2014年ChengZhifeng. All rights reserved.
//
#import
#import
@interfaceNoteManagedObject :NSManagedObject
@property(nonatomic,retain)NSDate* date;
@property(nonatomic,retain)NSString* content;
@end
//
//NoteManagedObject.m
//NoteCoreDataLearn
//
//Created by ChengDavid on 14-7-6.
//Copyright (c) 2014年ChengZhifeng. All rights reserved.
//
#import"NoteManagedObject.h"
@implementationNoteManagedObject
@dynamicdate;
@dynamiccontent;
@end
//
//Note.h
//NoteCoreDataLearn
//
//Created by ChengDavid on 14-7-6.
//Copyright (c) 2014年ChengZhifeng. All rights reserved.
//
#import
@interfaceNote :NSObject
@property(nonatomic,strong)NSDate*date;
@property(nonatomic,strong)NSString*content;
@end
//
//Note.m
//NoteCoreDataLearn
//
//Created by ChengDavid on 14-7-6.
//Copyright (c) 2014年ChengZhifeng. All rights reserved.
//
#import"Note.h"
@implementationNote
@end
//
//CoreDataDAO.h
//PersistenceLayer
//
//
#import
#import
@interfaceCoreDataDAO :NSObject
//被管理的对象上下文
@property(readonly,strong,nonatomic)NSManagedObjectContext*managedObjectContext;
//被管理的对象模型
@property(readonly,strong,nonatomic)NSManagedObjectModel*managedObjectModel;
//持久化存储协调者
@property(readonly,strong,nonatomic)NSPersistentStoreCoordinator*persistentStoreCoordinator;
- (NSURL*)applicationDocumentsDirectory;
@end
//
//CoreDataDAO.m
//PersistenceLayer
//
//
#import"CoreDataDAO.h"
@implementationCoreDataDAO
@synthesizemanagedObjectContext =_managedObjectContext;
@synthesizemanagedObjectModel =_managedObjectModel;
@synthesizepersistentStoreCoordinator =_persistentStoreCoordinator;
#pragma mark - Core Data堆栈
//返回 被管理的对象上下文
- (NSManagedObjectContext*)managedObjectContext
{
if(_managedObjectContext) {
return_managedObjectContext;
}
NSPersistentStoreCoordinator*coordinator = [selfpersistentStoreCoordinator];
if(coordinator) {
_managedObjectContext= [[NSManagedObjectContextalloc]init];
[_managedObjectContextsetPersistentStoreCoordinator:coordinator];
}
return_managedObjectContext;
}
//返回 持久化存储协调者
- (NSPersistentStoreCoordinator*)persistentStoreCoordinator
{
if(_persistentStoreCoordinator) {
return_persistentStoreCoordinator;
}
//数据库文件
NSURL*storeURL = [[selfapplicationDocumentsDirectory]URLByAppendingPathComponent:@"CoreDataNotes.sqlite"];
_persistentStoreCoordinator= [[NSPersistentStoreCoordinatoralloc]initWithManagedObjectModel:[selfmanagedObjectModel]];
[_persistentStoreCoordinatoraddPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:storeURL
options:nil
error:nil];
return_persistentStoreCoordinator;
}
//返回 被管理的对象模型
- (NSManagedObjectModel*)managedObjectModel
{
if(_managedObjectModel) {
return_managedObjectModel;
}
//模型文件
NSURL*modelURL = [[NSBundlemainBundle]URLForResource:@"CoreDataNotes"withExtension:@"momd"];
_managedObjectModel= [[NSManagedObjectModelalloc]initWithContentsOfURL:modelURL];
return_managedObjectModel;
}
#pragma mark -应用程序沙箱
//返回应用程序Docment目录的NSURL类型
- (NSURL*)applicationDocumentsDirectory
{
return[[[NSFileManagerdefaultManager]URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask]lastObject];
}
@end
//
//NoteDAO.h
//MyNotes
//
//
#import
#import"CoreDataDAO.h"
#import"Note.h"
#import"NoteManagedObject.h"
@interfaceNoteDAO :CoreDataDAO
+ (NoteDAO*)sharedManager;
//插入Note方法
-(int) create:(Note*)model;
//删除Note方法
-(int) remove:(Note*)model;
//修改Note方法
-(int) modify:(Note*)model;
//查询所有数据方法
-(NSMutableArray*) findAll;
//按照主键查询数据方法
-(Note*) findById:(Note*)model;
@end
//
//NoteDAO.m
//MyNotes
//
#import"NoteDAO.h"
@implementationNoteDAO
staticNoteDAO*sharedManager =nil;
+ (NoteDAO*)sharedManager
{
staticdispatch_once_tonce;
dispatch_once(&once, ^{
sharedManager= [[selfalloc]init];
[sharedManagermanagedObjectContext];
});
returnsharedManager;
}
//插入Note方法
-(int) create:(Note*)model
{
NSManagedObjectContext*cxt = [selfmanagedObjectContext];
NoteManagedObject*note = [NSEntityDescriptioninsertNewObjectForEntityForName:@"Note"inManagedObjectContext:cxt];
[notesetValue: model.contentforKey:@"content"];
[notesetValue: model.dateforKey:@"date"];
note.date= model.date;
note.content= model.content;
NSError*savingError =nil;
if([self.managedObjectContextsave:&savingError]){
NSLog(@"插入数据成功");
}else{
NSLog(@"插入数据失败");
return-1;
}
return0;
}
//删除Note方法
-(int) remove:(Note*)model
{
NSManagedObjectContext*cxt = [selfmanagedObjectContext];
NSEntityDescription*entityDescription = [NSEntityDescription
entityForName:@"Note"inManagedObjectContext:cxt];
NSFetchRequest*request = [[NSFetchRequestalloc]init];
[requestsetEntity:entityDescription];
NSPredicate*predicate = [NSPredicatepredicateWithFormat:
@"date =%@", model.date];
[requestsetPredicate:predicate];
NSError*error =nil;
NSArray*listData = [cxtexecuteFetchRequest:requesterror:&error];
if([listDatacount] >0) {
NoteManagedObject*note = [listDatalastObject];
[self.managedObjectContextdeleteObject:note];
NSError*savingError =nil;
if([self.managedObjectContextsave:&savingError]){
NSLog(@"删除数据成功");
}else{
NSLog(@"删除数据失败");
return-1;
}
}
return0;
}
//修改Note方法
-(int) modify:(Note*)model
{
NSManagedObjectContext*cxt = [selfmanagedObjectContext];
NSEntityDescription*entityDescription = [NSEntityDescription
entityForName:@"Note"inManagedObjectContext:cxt];
NSFetchRequest*request = [[NSFetchRequestalloc]init];
[requestsetEntity:entityDescription];
NSPredicate*predicate = [NSPredicatepredicateWithFormat:
@"date =%@", model.date];
[requestsetPredicate:predicate];
NSError*error =nil;
NSArray*listData = [cxtexecuteFetchRequest:requesterror:&error];
if([listDatacount] >0) {
NoteManagedObject*note = [listDatalastObject];
note.content= model.content;
NSError*savingError =nil;
if([self.managedObjectContextsave:&savingError]){
NSLog(@"修改数据成功");
}else{
NSLog(@"修改数据失败");
return-1;
}
}
return0;
}
//查询所有数据方法
-(NSMutableArray*) findAll
{
NSManagedObjectContext*cxt = [selfmanagedObjectContext];
NSEntityDescription*entityDescription = [NSEntityDescription
entityForName:@"Note"inManagedObjectContext:cxt];
NSFetchRequest*request = [[NSFetchRequestalloc]init];
[requestsetEntity:entityDescription];
NSSortDescriptor*sortDescriptor = [[NSSortDescriptoralloc]initWithKey:@"date"ascending:YES];
[requestsetSortDescriptors:@[sortDescriptor]];
NSError*error =nil;
NSArray*listData = [cxtexecuteFetchRequest:requesterror:&error];
NSMutableArray*resListData = [[NSMutableArrayalloc]init];
for(NoteManagedObject*moinlistData) {
Note*note = [[Notealloc]init];
note.date= mo.date;
note.content= mo.content;
[resListDataaddObject:note];
}
returnresListData;
}
//按照主键查询数据方法
-(Note*) findById:(Note*)model
{
NSManagedObjectContext*cxt = [selfmanagedObjectContext];
NSEntityDescription*entityDescription = [NSEntityDescription
entityForName:@"Note"inManagedObjectContext:cxt];
NSFetchRequest*request = [[NSFetchRequestalloc]init];
[requestsetEntity:entityDescription];
NSPredicate*predicate = [NSPredicatepredicateWithFormat:
@"date =%@",model.date];
[requestsetPredicate:predicate];
NSError*error =nil;
NSArray*listData = [cxtexecuteFetchRequest:requesterror:&error];
if([listDatacount] >0) {
NoteManagedObject*mo = [listDatalastObject];
Note*note = [[Notealloc]init];
note.date= mo.date;
note.content= mo.content;
returnnote;
}
return nil;
}
@end
//
//NoteBL.h
//NoteCoreDataLearn
//
//Created by ChengDavid on 14-7-6.
//Copyright (c) 2014年ChengZhifeng. All rights reserved.
//
#import
#import"Note.h"
#import"NoteDAO.h"
@interfaceNoteBL :NSObject
//插入Note方法
-(NSMutableArray*)createNote:(Note*)model;
//删除note方法
-(NSMutableArray*)remove:(Note*)model;
//查询所有数据方法
-(NSMutableArray*)findAll;
//修改note方法
-(NSMutableArray*)modify:(Note*)model;
@end
//
//NoteBL.m
//NoteCoreDataLearn
//
//Created by ChengDavid on 14-7-6.
//Copyright (c) 2014年ChengZhifeng. All rights reserved.
//
#import"NoteBL.h"
@implementationNoteBL
//插入Note方法
-(NSMutableArray*)createNote:(Note*)model
{
NoteDAO*dao=[NoteDAOsharedManager];
[daocreate:model];
return[daofindAll];
}
//删除note方法
-(NSMutableArray*)remove:(Note*)model
{
NoteDAO*dao=[NoteDAOsharedManager];
[daoremove:model];
return[daofindAll];
}
//修改note方法
-(NSMutableArray*)modify:(Note*)model
{
NoteDAO*dao=[NoteDAOsharedManager];
[daomodify:model];
return[daofindAll];
}
//查询所有数据方法
-(NSMutableArray*)findAll
{
NoteDAO*dao=[NoteDAOsharedManager];
return[daofindAll];
}
@end
需要提一下的是,这里的NoteDAO用到了单例模式。NoteBL则不需要单例模式。
sqlite文件则会自动在document文件夹下生成,无需理会。用sqlitemanger看了下,里面的数据是不加密的
附上测试的代码
//找到数据库文件的路径。可以观察到自动生成的数据库文件
- (IBAction)test:(id)sender {
NSArray*paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString*documentsDirectory = [pathsobjectAtIndex:0];
NSLog(@"路径:%@",documentsDirectory);
}
- (IBAction)create:(id)sender {
NoteBL*noteBl=[[NoteBLalloc]init];
Note*note=[[Notealloc]init];
note.date= [[NSDatealloc]init];
note.content=@"hello world";
NSMutableArray*dataList = [noteBlcreateNote:note];
intlength = dataList.count;
for(inti=0;i
Note*tmp = [dataListobjectAtIndex:i];
NSLog(@"------%d",i);
NSLog(@"date:%@",tmp.date);
NSLog(@"content:%@",tmp.content);
}
}
- (IBAction)remove:(id)sender {
NoteBL*noteBl=[[NoteBLalloc]init];
NSMutableArray*dataList = [noteBlfindAll];
intlength = dataList.count;
NSLog(@"删之前:%d条记录",length);
if(length<=0)return;
Note*tmp = [dataListobjectAtIndex:length-1];
[noteBlremove:tmp];
dataList = [noteBlfindAll];
length = dataList.count;
NSLog(@"删之后:%d条记录",length);
}
- (IBAction)modify:(id)sender {
NoteBL*noteBl=[[NoteBLalloc]init];
NSMutableArray*dataList = [noteBlfindAll];
NSLog(@"修改之前:");
Note*tmp = [dataListobjectAtIndex:0];
NSLog(@"date:%@",tmp.date);
NSLog(@"content:%@",tmp.content);
[tmpsetContent:@"hhahahhahahhaha"];
dataList = [noteBlmodify:tmp];
NSLog(@"修改之后:");
tmp = [dataListobjectAtIndex:0];
NSLog(@"date:%@",tmp.date);
NSLog(@"content:%@",tmp.content);
}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。