CoreData入門

本文作為筆者自己的備忘錄,由淺至深的記錄學(xué)習(xí)過程

一:添加庫
Snip20161201_1.png
二:添加CoreDataHelper類

.h文件

//
//  CoreDataHelper.h
//  CoreDate學(xué)習(xí)
//
//  Created by 王一 on 2016/11/28.
//  Copyright ? 2016年 wangyi. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>

@interface CoreDataHelper : NSObject

@property(nonatomic,strong,readonly)NSManagedObjectContext *context;
@property(nonatomic,strong,readonly)NSManagedObjectModel *model;
@property(nonatomic,strong,readonly)NSPersistentStoreCoordinator *coordinator;
@property(nonatomic,strong,readonly)NSPersistentStore   *store;

-(void)setupCoreData;
-(void)saveContext;

@end

.m文件

//
//  CoreDataHelper.m
//  CoreDate學(xué)習(xí)
//
//  Created by 王一 on 2016/11/28.
//  Copyright ? 2016年 wangyi. All rights reserved.
//
#define debug 1
#import "CoreDataHelper.h"

@implementation CoreDataHelper

#pragma mark - FILES
//存儲文件名
NSString *storeFilename = @"2016121.sqlite";

#pragma mark - PATHS
//程序文檔目錄路徑
-(NSString *)applicationDocumentsDirectory{
    if (debug == 1) {
        NSLog(@"Running %@ '%@'",self.class,NSStringFromSelector(_cmd));
    }
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}

//向應(yīng)用程序文檔目錄中添加名為Stores的子目錄
-(NSURL *)applicationStoresDirectory{
    if (debug == 1) {
        NSLog(@"Running %@ '%@'",self.class,NSStringFromSelector(_cmd));
    }
    NSURL *storesDirectory = [[NSURL fileURLWithPath:[self applicationDocumentsDirectory]] URLByAppendingPathComponent:@"Stores"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:[storesDirectory path]]) {
        NSError *error = nil;
        if ([fileManager createDirectoryAtURL:storesDirectory withIntermediateDirectories:YES attributes:nil error:&error]) {
            if (debug == 1) {
                NSLog(@"Successfully created Stores directory");
            }
        }else{
            NSLog(@"FAILED to create Stores directory: %@",error);
        }
    }
    return storesDirectory;
}

//存儲區(qū)的文件名添加到Store目錄的路徑中
-(NSURL *)storeURL{
    if (debug == 1) {
        NSLog(@"Running %@ '%@'",self.class,NSStringFromSelector(_cmd));
    }
    return [[self applicationStoresDirectory] URLByAppendingPathComponent:storeFilename];
}

#pragma mark - SETUP
//初始化Core Data三個方法
-(id)init{
    if (debug == 1) {
        NSLog(@"Running %@ '%@'",self.class,NSStringFromSelector(_cmd));
    }
    self = [super init];
    if (self == nil) {
        return nil;
    }
    _model = [NSManagedObjectModel mergedModelFromBundles:nil];
    _coordinator = [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:_model];
    _context = [[NSManagedObjectContext alloc]initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_context setPersistentStoreCoordinator:_coordinator];
    return self;
}

-(void)loadStore{
    if (debug == 1) {
        NSLog(@"Running %@ '%@'",self.class,NSStringFromSelector(_cmd));
    }
    if (_store) {
        return;
    }
    
    NSDictionary *options = @{
                              NSMigratePersistentStoresAutomaticallyOption:@YES,
                              NSInferMappingModelAutomaticallyOption:@YES,
                              NSSQLitePragmasOption: @{@"journal_mode": @"DELETE"}
                              };
    
    NSError *error = nil;
    _store = [_coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[self storeURL] options:options error:&error];
    if (_store == nil) {
        NSLog(@"Failed to add store.Error:%@",error);
        abort();
    }else{
        if (debug == 1) {
            NSLog(@"Successfully added store: %@",_store);
        }
    }
}

-(void)setupCoreData{
    if (debug == 1) {
        NSLog(@"Running %@ '%@'",self.class,NSStringFromSelector(_cmd));
    }
    [self loadStore];
}

#pragma mark - SAVING

-(void)saveContext{
    if (debug == 1) {
        NSLog(@"Running %@ '%@'",self.class,NSStringFromSelector(_cmd));
    }
    if ([_context hasChanges]) {
        NSError *error = nil;
        if ([_context save:&error]) {
            NSLog(@"_context SAVED changes to persistent store");
        }else{
            NSLog(@"Failed to save _context: %@",error);
        }
    }else{
        NSLog(@"SKIPPED _context save,there are no changes!");
    }
}
@end

三:添加、刪除、排序、篩選的一些簡單操作

注意:排序和篩選很少會寫代碼,用的是Xcode請求模板,功能強大,簡單,這里只是為了記錄

    //插入數(shù)據(jù)
    NSArray *namesArray = [NSArray arrayWithObjects:@"a王一", @"a劉洋", @"c陳攀科", @"b韓熙", @"e趙密柱", @"f王楠俠", @"g沈建", @"h付曉奎", nil];
    for (NSString *nameString in namesArray) {
        Item *itemArray = [NSEntityDescription insertNewObjectForEntityForName:@"Item" inManagedObjectContext:_coreDataHelper.context];
        itemArray.name = nameString;
        NSLog(@"%@",itemArray.name);
    }

    //獲取數(shù)據(jù)
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Item"];
    NSArray *array = [_coreDataHelper.context executeFetchRequest:request error:nil];
    for (Item *itemArray in array) {
        NSLog(@"itemArray = %@",itemArray.name);
    }

    //排序
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Item"];
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
    [request setSortDescriptors:[NSArray arrayWithObject:sort]];
    NSArray *array = [_coreDataHelper.context executeFetchRequest:request error:nil];
    for (Item *itemArray in array) {
        NSLog(@"itemArray = %@",itemArray.name);
    }

    //查找篩選 前50條
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Item"];
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
    [request setSortDescriptors:[NSArray arrayWithObject:sort]];
    [request setFetchLimit:50];
    NSPredicate *filer = [NSPredicate predicateWithFormat:@"name != %@",@"一"];
    [request setPredicate:filer];
    NSArray *array = [_coreDataHelper.context executeFetchRequest:request error:nil];
    for (Item *itemArray in array) {
        NSLog(@"itemArray = %@",itemArray.name);
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • CoreData 是 iOS3.0 時引入的一個數(shù)據(jù)持久化的框架。他與 sqlite 對比最大的優(yōu)點莫過于支持對象...
    獨奏閱讀 6,684評論 2 19
  • 一、判斷是否適合使用Core Data 要使用持久化數(shù)據(jù),我們有多種選擇: 1.NSUserDefaults: ...
    奧斯丁1_1閱讀 254評論 1 2
  • CoreData入門 CoreData是蘋果提供的實現(xiàn)SQLite關(guān)系型數(shù)據(jù)庫的持久化的框架,具有面向?qū)ο罄砟詈蛯?..
    LennonLin閱讀 358評論 0 3
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,540評論 4 61
  • 有時候 我們見到一個人,并不感覺其讓人多么心神愉快,讓人有交流的渴望, 但事后想起,這個人總讓人覺得 應(yīng)該是一個聊...
    你要努力呀火星寶寶閱讀 958評論 0 1

友情鏈接更多精彩內(nèi)容