本文作為筆者自己的備忘錄,由淺至深的記錄學(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);
}