1. 今天的课程、 大家在学习之后肯定会有另一番想法、
至少、 你们会收藏我的博客吧、嘿嘿、 新开的人气可不怎么高
2. 好、 废话不多说、 直接切入正题、 网上讲coreData的有好多、 但大多数不怎么细致、 也不会完整的敲代码、
所以、 今天上午我自己简单的封装一下coreData供自己使用。 大家可以借鉴一下。 又不足之处还望指出。
3. 开始编码:
1. 导入 coreData.FrameWork 我们今天封装的东西、 不实用系统自带的coreData、 而是导入库自己去写。 加深印象
思想: 单例 + 中间层 (中间层继承于NSManagedObject 方便我们操作、 也有住于在业务量大的时候优化代码)
总共4个文件 我们开始编码:
1、单例 ADCoreData.h
1 // 2 // ADCoreData.h 3 // CoreData_CE 4 // 5 // Created by Dylan on 14-10-11. 6 // Copyright (c) 2014年 Dylan. All rights reserved. 7 // 8 9 /*!10 * @Author Dylan.11 *12 * Please add CoreData.FrameWork13 */14 15 #import16 #import 17 18 @interface ADCoreData : NSObject19 20 /*!21 * @Author Dylan.22 *23 * context24 */25 @property (nonatomic, strong, readonly) NSManagedObjectContext * manageContext;26 27 + (instancetype)shareInstanceWithStoreName: (NSString *)storeName;28 29 /*!30 * @Author Dylan.31 *32 * Methods33 */34 35 - (NSMutableArray *)findByModel: (id)model;36 - (NSMutableArray *)findByModel: (id)model37 predicateString: (NSString *)predicateString;38 /*!39 * Update40 */41 - (BOOL)create: (id)model;42 43 - (BOOL)remove: (id)model;44 - (BOOL)remove: (id)model45 predicateString: (NSString *)predicateString;46 - (BOOL)modify: (id)model47 predicateString: (NSString *)predicateString;48 49 @end
ADCoreData.m
1 // 2 // ADCoreData.m 3 // CoreData_CE 4 // 5 // Created by Dylan on 14-10-11. 6 // Copyright (c) 2014年 Dylan. All rights reserved. 7 // 8 9 #import "ADCoreData.h" 10 #import "ADCoreDataManager.h" 11 #import12 13 #define CLASS_NAME(PRAM) NSStringFromClass([PRAM class]) 14 15 @interface ADCoreData () 16 17 @property (nonatomic, strong) NSManagedObjectModel * managedobjectModel; 18 @property (nonatomic, strong) NSPersistentStoreCoordinator * persistentStoreCoordinator; 19 20 /*! 21 * @Author Dylan. 22 * 23 * storeName 24 */ 25 @property (nonatomic, strong) NSString * storeName; 26 27 - (NSURL *)applicationDomainUrl; 28 29 @end 30 31 static ADCoreData * coreData; 32 33 @implementation ADCoreData 34 35 + (instancetype)shareInstanceWithStoreName:(NSString *)storeName { 36 static dispatch_once_t onceToken; 37 dispatch_once(&onceToken, ^{ 38 coreData = [[self alloc] init]; 39 coreData.storeName = storeName; 40 }); 41 42 return coreData; 43 } 44 45 /*! 46 * @Author Dylan. 47 * 48 * synthesize 49 */ 50 @synthesize manageContext = _manageContext; 51 @synthesize managedobjectModel = _managedobjectModel; 52 @synthesize persistentStoreCoordinator = _persistentStoreCoordinator; 53 54 #pragma mark - 55 #pragma mark - GET 56 - (NSManagedObjectContext *)manageContext { 57 58 if (_manageContext) { 59 return _manageContext; 60 } 61 62 NSPersistentStoreCoordinator * coordinator = [self persistentStoreCoordinator]; 63 if (coordinator != nil) { 64 _manageContext = [[NSManagedObjectContext alloc] init]; 65 [_manageContext setPersistentStoreCoordinator:coordinator]; 66 } 67 return _manageContext; 68 } 69 70 - (NSPersistentStoreCoordinator *)persistentStoreCoordinator { 71 72 if (_persistentStoreCoordinator) { 73 return _persistentStoreCoordinator; 74 } 75 76 NSURL * storeUrl = [[self applicationDomainUrl] URLByAppendingPathComponent:[NSString stringWithFormat:@"%@.sqlite", _storeName]]; 77 _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.managedobjectModel]; 78 [_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:nil]; 79 return _persistentStoreCoordinator; 80 } 81 82 - (NSManagedObjectModel *)managedobjectModel { 83 84 if (_managedobjectModel) { 85 return _managedobjectModel; 86 } 87 88 NSURL * modelUrl = [[NSBundle mainBundle] URLForResource:_storeName withExtension:@"momd"]; 89 _managedobjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelUrl]; 90 return _managedobjectModel; 91 } 92 93 #pragma mark - Methods 94 - (NSMutableArray *)findByModel: (id)model { 95 96 NSError * error = nil; 97 NSArray * listArray = [_manageContext executeFetchRequest:[self bindRequest:CLASS_NAME(model) predicate:nil] error:&error]; 98 NSMutableArray * resultArray = [NSMutableArray array]; 99 100 for (ADCoreDataManager * manager in listArray) {101 102 for (NSString * propertyName in [self ClassAttributes:model]) {103 [model setValue:[manager valueForKey:propertyName] forKey:propertyName];104 }105 [resultArray addObject:model];106 }107 return resultArray;108 }109 110 - (NSMutableArray *)findByModel: (id)model111 predicateString: (NSString *)predicateString; {112 113 NSError * error = nil;114 NSArray * listArray = [_manageContext executeFetchRequest:[self bindRequest:CLASS_NAME(model) predicate:predicateString] error:&error];115 NSMutableArray * resultArray = [NSMutableArray array];116 117 if (listArray.count >= 1) {118 for (ADCoreDataManager * manager in listArray) {119 120 for (NSString * propertyName in [self ClassAttributes:model]) {121 [model setValue:[manager valueForKey:propertyName] forKey:propertyName];122 }123 [resultArray addObject:model];124 }125 }126 return resultArray;127 }128 129 #pragma mark update130 - (BOOL)create: (id)model {131 ADCoreDataManager * manager = [NSEntityDescription insertNewObjectForEntityForName:CLASS_NAME(model) inManagedObjectContext:_manageContext];132 133 for (NSString * propertyName in [self ClassAttributes:model]) {134 [manager setValue:[model valueForKey:propertyName] forKey:propertyName];135 }136 BOOL result = [self saveContext];137 return result;138 }139 140 - (BOOL)remove: (id)model {141 142 NSError * error = nil;143 NSArray * listArray = [_manageContext executeFetchRequest:[self bindRequest:CLASS_NAME(model) predicate:nil] error:&error];144 if (listArray.count > 0) {145 for (ADCoreDataManager * manager in listArray) {146 [_manageContext deleteObject:manager];147 }148 }149 return [self saveContext];150 }151 152 - (BOOL)remove: (id)model153 predicateString: (NSString *)predicateString {154 155 NSError * error = nil;156 NSArray * listArray = [_manageContext executeFetchRequest:[self bindRequest:CLASS_NAME(model) predicate:predicateString] error:&error];157 158 if (listArray.count > 0) {159 for (ADCoreDataManager * manager in listArray) {160 [_manageContext deleteObject:manager];161 }162 }163 return [self saveContext];164 }165 166 - (BOOL)modify: (id)model167 predicateString: (NSString *)predicateString {168 169 NSError * error = nil;170 NSArray * listArray = [_manageContext executeFetchRequest:[self bindRequest:CLASS_NAME(model) predicate:predicateString] error:&error];171 172 if (listArray.count > 0) {173 174 for (ADCoreDataManager * manager in listArray) {175 for (NSString * propertyName in [self ClassAttributes:model]) {176 [manager setValue:[model valueForKey:propertyName] forKey:propertyName];177 }178 }179 }180 return [self saveContext];181 }182 183 #pragma mark - collect184 - (NSFetchRequest *)bindRequest: (NSString *)className185 predicate: (NSString *)predicateString {186 NSFetchRequest * request = [[NSFetchRequest alloc] init];187 [request setEntity:[NSEntityDescription entityForName:className inManagedObjectContext:_manageContext]];188 189 if (predicateString != nil) {190 NSPredicate * predicate = [NSPredicate predicateWithFormat:predicateString];191 NSLog(@"%@", predicate);192 NSLog(@"%@", predicateString);193 [request setPredicate:predicate];194 }195 return request;196 }197 198 199 #pragma mark - save200 - (BOOL)saveContext {201 202 NSManagedObjectContext * context = [self manageContext];203 if (context != nil) {204 205 NSError * error = nil;206 if ([context hasChanges] && ![context save:&error]) {207 NSLog(@"%@", [error userInfo]);208 abort();209 return NO;210 }211 }212 213 return YES;214 }215 216 217 - (NSURL *)applicationDomainUrl {218 return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];219 }220 221 #pragma mark - allAttributes222 - (NSMutableArray *) ClassAttributes: (id)classModel {223 224 NSMutableArray * array = [NSMutableArray array];225 NSString *className = NSStringFromClass([classModel class]);226 const char * cClassName = [className UTF8String];227 228 id classM = objc_getClass(cClassName);229 unsigned int outCount, i;230 objc_property_t * properties = class_copyPropertyList(classM, &outCount);231 for (i = 0; i < outCount; i++) {232 objc_property_t property = properties[i];233 NSString * attributeName = [NSString stringWithUTF8String:property_getName(property)];234 235 [array addObject:attributeName];236 }237 return array;238 }239 240 @end
在m文件中, 我使用了运行时。 运行时拿到一个模型的属性 这样我们可以更加方便的使用KVC
大家仔细看一下这种封装的过程
2.中间层: ADCoreDataManager.h
1 // 2 // ADCoreDataManager.h 3 // CoreData_CE 4 // 5 // Created by Dylan on 14-10-11. 6 // Copyright (c) 2014年 Dylan. All rights reserved. 7 // 8 9 #warning add Model properties Here10 11 #import12 #import 13 14 @interface ADCoreDataManager : NSManagedObject15 16 /*!17 * @Author Dylan.18 *19 * e.g20 */21 @property (nonatomic, strong) NSString * name;22 23 @end
.m文件
1 // 2 // ADCoreDataManager.m 3 // CoreData_CE 4 // 5 // Created by Dylan on 14-10-11. 6 // Copyright (c) 2014年 Dylan. All rights reserved. 7 // 8 9 #warning don't forget write @synthesize10 11 #import "ADCoreDataManager.h"12 13 @implementation ADCoreDataManager14 15 @synthesize name = _name;16 17 - (void)setValue:(id)value forUndefinedKey:(NSString *)key {18 19 }20 21 @end
大家可以把所有模型的属性 扔到中间层里边。 使用中间层去做中介传值。
使用:
1. 创建自己的momd文件。 新建-》coredata-》model 创建之后添加模型
2. 初始化单例
附上测试代码
1 // test 2 ADCoreData * coreData = [ADCoreData shareInstanceWithStoreName:@"CoreData"]; 3 4 Dylan * dylan = [[Dylan alloc] initWithEntity:[NSEntityDescription entityForName:@"Dylan" inManagedObjectContext:coreData.manageContext] insertIntoManagedObjectContext:nil]; 5 [dylan setName:@"Dylan"]; 6 7 NSLog(@"**************************************************"); 8 9 NSLog(@"first = %@", [coreData findByModel:dylan]);10 11 NSLog(@"**************************************************");12 13 [coreData create:dylan];14 NSLog(@"second = %@", [coreData findByModel:dylan]);15 NSLog(@"third = %@", [coreData findByModel:dylan predicateString:@"name = 'Dylan'"]);16 NSLog(@"**************************************************");17 18 [coreData remove:dylan];19 NSLog(@"fourth = %@", [coreData findByModel:dylan]);20 NSLog(@"**************************************************");21 22 [coreData create:dylan];23 NSLog(@"fifth = %@", [coreData findByModel:dylan]);24 25 NSLog(@"**************************************************");26 27 Dylan * dylan1 = [[Dylan alloc] initWithEntity:[NSEntityDescription entityForName:@"Dylan" inManagedObjectContext:coreData.manageContext] insertIntoManagedObjectContext:nil];28 dylan1.name = @"dylan-1";29 30 [coreData modify:dylan1 predicateString:nil];31 NSLog(@"sixth = %@", [coreData findByModel:dylan]);32 NSLog(@"seventh = %@", [coreData findByModel:dylan1]);
CoreData书写虽然比较难, 但是操作方便
大家在使用谓词的时候 要特别的注意 在你的值上边加单引号 类似: name = 'Dylan' 防止CoreData在操作request请求时候出现错误
@Dylan.