CoreData入门

本文作为笔者自己的备忘录,由浅至深的记录学习过程
一:添加库 CoreData入门
文章图片
Snip20161201_1.png 二:添加CoreDataHelper类 .h文件

// //CoreDataHelper.h //CoreDate学习 // //Created by 王一 on 2016/11/28. //Copyright ? 2016年 wangyi. All rights reserved. //#import #import @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学习 // //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]; }//向应用程序文档目录中添加名为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; }//存储区的文件名添加到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

三:添加、删除、排序、筛选的一些简单操作 【CoreData入门】注意:排序和筛选很少会写代码,用的是Xcode请求模板,功能强大,简单,这里只是为了记录
//插入数据 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); }//获取数据 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); }

    推荐阅读