CoreData使用

发布时间:2020-07-22 15:50:02 作者:卓行天下
来源:网络 阅读:320

//  NoteManagedObject.h

//  NoteCoreDataLearn

//

//  Created by ChengDavid on 14-7-6.

//  Copyright (c) 2014 ChengZhifeng. All rights reserved.

//


#import

#import



@interface NoteManagedObject : 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"



@implementation NoteManagedObject


@dynamic date;

@dynamic content;


@end

//

//  Note.h

//  NoteCoreDataLearn

//

//  Created by ChengDavid on 14-7-6.

//  Copyright (c) 2014 ChengZhifeng. All rights reserved.

//

#import

@interface Note : 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"


@implementation Note


@end

//

//  CoreDataDAO.h

//  PersistenceLayer

//

//


#import

#import


@interface CoreDataDAO : NSObject



//被管理的对象上下文

@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;

//被管理的对象模型

@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;

//持久化存储协调者

@property (readonlystrongnonatomicNSPersistentStoreCoordinator *persistentStoreCoordinator;


- (NSURL *)applicationDocumentsDirectory;


@end

//

//  CoreDataDAO.m

//  PersistenceLayer

//


//


#import "CoreDataDAO.h"


@implementation CoreDataDAO


@synthesize managedObjectContext = _managedObjectContext;

@synthesize managedObjectModel = _managedObjectModel;

@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;



#pragma mark - Core Data 堆栈

//返回 被管理的对象上下文

- (NSManagedObjectContext *)managedObjectContext

{

    if (_managedObjectContext) {

        return _managedObjectContext;

    }

    

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];

    if (coordinator) {

        _managedObjectContext = [[NSManagedObjectContext alloc] init];

        [_managedObjectContext setPersistentStoreCoordinator:coordinator];

    }

    return _managedObjectContext;

}


// 返回 持久化存储协调者

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator

{

    if (_persistentStoreCoordinator) {

        return _persistentStoreCoordinator;

    }

    

  //数据库文件

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreDataNotes.sqlite"];

    

    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[selfmanagedObjectModel]];

    

    [_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType

                      configuration:nil

                                URL:storeURL

                            options:nil

                              error:nil];

    

    return _persistentStoreCoordinator;

}


//  返回 被管理的对象模型

- (NSManagedObjectModel *)managedObjectModel

{

    if (_managedObjectModel) {

        return _managedObjectModel;

    }

//模型文件

    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"CoreDataNotes" withExtension:@"momd"];

    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

    return _managedObjectModel;

}


#pragma mark - 应用程序沙箱

// 返回应用程序Docment目录的NSURL类型

- (NSURL *)applicationDocumentsDirectory

{

    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];

}


@end

//

//  NoteDAO.h

//  MyNotes

//

//

#import

#import "CoreDataDAO.h"

#import "Note.h"

#import "NoteManagedObject.h"

@interface NoteDAO : 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"

@implementation NoteDAO


static NoteDAO *sharedManager = nil;


+ (NoteDAO*)sharedManager

{

    static dispatch_once_t once;

    dispatch_once(&once, ^{

        

        sharedManager = [[self allocinit];

        [sharedManager managedObjectContext];

        

    });

    return sharedManager;

}

//插入Note方法

-(int) create:(Note*)model

{

    

    NSManagedObjectContext *cxt = [self managedObjectContext];

    

    NoteManagedObject *note = [NSEntityDescription insertNewObjectForEntityForName:@"Note"inManagedObjectContext:cxt];

    [note setValue: model.content forKey:@"content"];

    [note setValue: model.date forKey:@"date"];

    

    note.date = model.date;

    note.content = model.content;

    

    NSError *savingError = nil;

    if ([self.managedObjectContext save:&savingError]){

        NSLog(@"插入数据成功");

    } else {

        NSLog(@"插入数据失败");

        return -1;

    }

    

    return 0;

}

//删除Note方法

-(int) remove:(Note*)model

{

    

    NSManagedObjectContext *cxt = [self managedObjectContext];

    

    NSEntityDescription *entityDescription = [NSEntityDescription

                                              entityForName:@"Note" inManagedObjectContext:cxt];

    

    NSFetchRequest *request = [[NSFetchRequest alloc] init];

    [request setEntity:entityDescription];

    

    NSPredicate *predicate = [NSPredicate predicateWithFormat:

                              @"date =  %@", model.date];

    [request setPredicate:predicate];

    

    NSError *error = nil;

    NSArray *listData = [cxt executeFetchRequest:request error:&error];

    if ([listData count] > 0) {

        NoteManagedObject *note = [listData lastObject];

        [self.managedObjectContext deleteObject:note];

        

        NSError *savingError = nil;

        if ([self.managedObjectContext save:&savingError]){

            NSLog(@"删除数据成功");

        } else {

            NSLog(@"删除数据失败");

            return -1;

        }

    }

    

    return 0;

}

//修改Note方法

-(int) modify:(Note*)model

{

    NSManagedObjectContext *cxt = [self managedObjectContext];

    

    NSEntityDescription *entityDescription = [NSEntityDescription

                                              entityForName:@"Note" inManagedObjectContext:cxt];

    

    NSFetchRequest *request = [[NSFetchRequest alloc] init];

    [request setEntity:entityDescription];

    

    NSPredicate *predicate = [NSPredicate predicateWithFormat:

                              @"date =  %@", model.date];

    [request setPredicate:predicate];

    

    NSError *error = nil;

    NSArray *listData = [cxt executeFetchRequest:request error:&error];

    if ([listData count] > 0) {

        NoteManagedObject *note = [listData lastObject];

        note.content = model.content;

        

        NSError *savingError = nil;

        if ([self.managedObjectContext save:&savingError]){

            NSLog(@"修改数据成功");

        } else {

            NSLog(@"修改数据失败");

            return -1;

        }

    }

    return 0;

}


//查询所有数据方法

-(NSMutableArray*) findAll

{

    NSManagedObjectContext *cxt = [self managedObjectContext];

    

    NSEntityDescription *entityDescription = [NSEntityDescription

                                              entityForName:@"Note" inManagedObjectContext:cxt];

    

    NSFetchRequest *request = [[NSFetchRequest alloc] init];

    [request setEntity:entityDescription];

    

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor allocinitWithKey:@"date" ascending:YES];

    [request setSortDescriptors:@[sortDescriptor]];

    

    NSError *error = nil;

    NSArray *listData = [cxt executeFetchRequest:request error:&error];

    

    NSMutableArray *resListData = [[NSMutableArray alloc] init];

    

    for (NoteManagedObject *mo in listData) {

        Note *note = [[Note allocinit];

        note.date = mo.date;

        note.content = mo.content;

        [resListData addObject:note];

    }

    

    return resListData;

}


//按照主键查询数据方法

-(Note*) findById:(Note*)model

{

    NSManagedObjectContext *cxt = [self managedObjectContext];

    

    NSEntityDescription *entityDescription = [NSEntityDescription

                                              entityForName:@"Note" inManagedObjectContext:cxt];

    

    NSFetchRequest *request = [[NSFetchRequest alloc] init];

    [request setEntity:entityDescription];

    

    NSPredicate *predicate = [NSPredicate predicateWithFormat:

                              @"date =  %@",model.date];

    [request setPredicate:predicate];

    

    NSError *error = nil;

    NSArray *listData = [cxt executeFetchRequest:request error:&error];

    

    if ([listData count] > 0) {

        NoteManagedObject *mo = [listData lastObject];

        

        Note *note = [[Note allocinit];

        note.date = mo.date;

        note.content = mo.content;

        

        return note;

    }

    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"


@interface NoteBL : 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"



@implementation NoteBL



//插入Note方法

-(NSMutableArray *)createNote:(Note *)model

{

    NoteDAO *dao=[NoteDAO sharedManager];

    [dao create:model];

    

    return [dao findAll];


}


//删除note方法

-(NSMutableArray *)remove:(Note *)model

{

    NoteDAO *dao=[NoteDAO sharedManager];

    [dao remove:model];

    

    return [dao findAll];

}


//修改note方法

-(NSMutableArray *)modify:(Note *)model

{

    NoteDAO *dao=[NoteDAO sharedManager];

    [dao modify:model];

    

    return [dao findAll];

}

//查询所有数据方法

-(NSMutableArray *)findAll

{

    NoteDAO *dao=[NoteDAO sharedManager];

    return [dao findAll];

}

@end

需要提一下的是,这里的NoteDAO用到了单例模式。NoteBL则不需要单例模式。

sqlite文件则会自动在document文件夹下生成,无需理会。用sqlitemanger看了下,里面的数据是不加密的

附上测试的代码

//找到数据库文件的路径。可以观察到自动生成的数据库文件

- (IBAction)test:(id)sender {

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSLog(@"路径:%@",documentsDirectory);

}


- (IBAction)create:(id)sender {

    NoteBL *noteBl=[[NoteBL allocinit];

    Note *note=[[Note allocinit];

    note.date = [[NSDate allocinit];

    note.content = @"hello world";

    

    NSMutableArray *dataList = [noteBl createNote:note];

    int length = dataList.count;

    for(int i=0;i

        Note *tmp = [dataList objectAtIndex:i];

        NSLog(@"------%d",i);

        NSLog(@"date:%@",tmp.date);

        NSLog(@"content:%@",tmp.content);

    }

}


- (IBAction)remove:(id)sender {

    NoteBL *noteBl=[[NoteBL allocinit];

    NSMutableArray *dataList = [noteBl findAll];

    int length = dataList.count;

    NSLog(@"删之前:%d条记录",length);

    

    if(length<=0) return;

    

    Note *tmp = [dataList objectAtIndex:length-1];

    [noteBl remove:tmp];

    

    dataList = [noteBl findAll];

    length = dataList.count;

    NSLog(@"删之后:%d条记录",length);

    

}


- (IBAction)modify:(id)sender {

    

    NoteBL *noteBl=[[NoteBL allocinit];

    NSMutableArray *dataList = [noteBl findAll];

    

    NSLog(@"修改之前:");

    Note *tmp = [dataList objectAtIndex:0];

    NSLog(@"date:%@",tmp.date);

    NSLog(@"content:%@",tmp.content);

    


    [tmp setContent:@"hhahahhahahhaha"];

    dataList = [noteBl modify:tmp];

    

    NSLog(@"修改之后:");

    tmp = [dataList objectAtIndex:0];

    NSLog(@"date:%@",tmp.date);

    NSLog(@"content:%@",tmp.content);

    

}

推荐阅读:
  1. laravel 使用 phpword使用说明
  2. Playground 你不知道的小技巧, CoreData 的使用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

模型 开发 记录

上一篇:简单了解tengine

下一篇:JavaScript直接调用函数与call调用有什么区别

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》