溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

CoreData使用

發(fā)布時(shí)間:2020-07-22 15:50:02 來(lái)源:網(wǎng)絡(luò) 閱讀:337 作者:卓行天下 欄目:開發(fā)技術(shù)

//  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



//被管理的對(duì)象上下文

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

//被管理的對(duì)象模型

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

//持久化存儲(chǔ)協(xié)調(diào)者

@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 堆棧

//返回 被管理的對(duì)象上下文

- (NSManagedObjectContext *)managedObjectContext

{

    if (_managedObjectContext) {

        return _managedObjectContext;

    }

    

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];

    if (coordinator) {

        _managedObjectContext = [[NSManagedObjectContext alloc] init];

        [_managedObjectContext setPersistentStoreCoordinator:coordinator];

    }

    return _managedObjectContext;

}


// 返回 持久化存儲(chǔ)協(xié)調(diào)者

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator

{

    if (_persistentStoreCoordinator) {

        return _persistentStoreCoordinator;

    }

    

  //數(shù)據(jù)庫(kù)文件

    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;

}


//  返回 被管理的對(duì)象模型

- (NSManagedObjectModel *)managedObjectModel

{

    if (_managedObjectModel) {

        return _managedObjectModel;

    }

//模型文件

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

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

    return _managedObjectModel;

}


#pragma mark - 應(yīng)用程序沙箱

// 返回應(yīng)用程序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;

//查詢所有數(shù)據(jù)方法

-(NSMutableArray*) findAll;

//按照主鍵查詢數(shù)據(jù)方法

-(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(@"插入數(shù)據(jù)成功");

    } else {

        NSLog(@"插入數(shù)據(jù)失敗");

        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(@"刪除數(shù)據(jù)成功");

        } else {

            NSLog(@"刪除數(shù)據(jù)失敗");

            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(@"修改數(shù)據(jù)成功");

        } else {

            NSLog(@"修改數(shù)據(jù)失敗");

            return -1;

        }

    }

    return 0;

}


//查詢所有數(shù)據(jù)方法

-(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;

}


//按照主鍵查詢數(shù)據(jù)方法

-(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;


//查詢所有數(shù)據(jù)方法

-(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];

}

//查詢所有數(shù)據(jù)方法

-(NSMutableArray *)findAll

{

    NoteDAO *dao=[NoteDAO sharedManager];

    return [dao findAll];

}

@end

需要提一下的是,這里的NoteDAO用到了單例模式。NoteBL則不需要單例模式。

sqlite文件則會(huì)自動(dòng)在document文件夾下生成,無(wú)需理會(huì)。用sqlitemanger看了下,里面的數(shù)據(jù)是不加密的

附上測(cè)試的代碼

//找到數(shù)據(jù)庫(kù)文件的路徑??梢杂^察到自動(dòng)生成的數(shù)據(jù)庫(kù)文件

- (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);

    

}

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI