大学IT网 - 最懂大学生的IT学习网站! QQ资料交流群:367606806
当前位置:大学IT网 > IOS技巧 > CoreData教学完整版(封装我们自己的CoreData工具)_Dylan

CoreData教学完整版(封装我们自己的CoreData工具)_Dylan

关键词:自己的完整版封装工具教学  阅读(4385) 赞(13)

[摘要]本文是对CoreData教学完整版(封装我们自己的CoreData工具)_Dylan的讲解,对学习IOS苹果软件开发有所帮助,与大家分享。

1. 今天的课程、 大家在学习之后肯定会有另一番想法、

至少、 你们会收藏我的博客吧、嘿嘿、 新开的人气可不怎么高

2. 好、 废话不多说、 直接切入正题、 网上讲coreData的有好多、 但大多数不怎么细致、 也不会完整的敲代码、

所以、 今天上午我自己简单的封装一下coreData供自己使用。 大家可以借鉴一下。 又不足之处还望指出。

3. 开始编码:

  1. 导入 coreData.FrameWork 我们今天封装的东西、 不实用系统自带的coreData、 而是导入库自己去写。 加深印象

  思想: 单例 + 中间层 (中间层继承于NSManagedObject 方便我们操作、 也有住于在业务量大的时候优化代码)

  总共4个文件 我们开始编码:

  1、单例 ADCoreData.h

  

 //
 //  ADCoreData.h
 //  CoreData_CE
 //
 //  Created by Dylan on 14-10-11.
 //  Copyright (c) 2014年 Dylan. All rights reserved.
 //
 
 /*!
  *  @Author Dylan.
  *
  *  Please add CoreData.FrameWork
  */
 
 #import <Foundation/Foundation.h>
 #import <CoreData/CoreData.h>
 
 @interface ADCoreData : NSObject
 
 /*!
  *  @Author Dylan.
  *
  *  context
  */
 @property (nonatomic, strong, readonly) NSManagedObjectContext * manageContext;
 
 + (instancetype)shareInstanceWithStoreName: (NSString *)storeName;
 
 /*!
  *  @Author Dylan.
  *
  *  Methods
  */
 
 - (NSMutableArray *)findByModel: (id)model;
 - (NSMutableArray *)findByModel: (id)model
                    predicateString: (NSString *)predicateString;
 /*!
  *  Update
  */
 - (BOOL)create: (id)model;
 
 - (BOOL)remove: (id)model;
 - (BOOL)remove: (id)model
       predicateString: (NSString *)predicateString;
 - (BOOL)modify: (id)model
  predicateString: (NSString *)predicateString;
 
 @end

  ADCoreData.m

 //
 //  ADCoreData.m
 //  CoreData_CE
 //
 //  Created by Dylan on 14-10-11.
 //  Copyright (c) 2014年 Dylan. All rights reserved.
 //
 
 #import "ADCoreData.h"
 #import "ADCoreDataManager.h"
 #import <objc/runtime.h>
 
 #define CLASS_NAME(PRAM) NSStringFromClass([PRAM class])
 
 @interface ADCoreData ()
 
 @property (nonatomic, strong) NSManagedObjectModel * managedobjectModel;
 @property (nonatomic, strong) NSPersistentStoreCoordinator * persistentStoreCoordinator;
 
 /*!
  *  @Author Dylan.
  *
  *  storeName
  */
 @property (nonatomic, strong) NSString * storeName;
 
 - (NSURL *)applicationDomainUrl;
 
 @end
 
 static ADCoreData * coreData;
 
 @implementation ADCoreData
 
 + (instancetype)shareInstanceWithStoreName:(NSString *)storeName {
     static dispatch_once_t onceToken;
     dispatch_once(&onceToken, ^{
         coreData = [[self alloc] init];
         coreData.storeName = storeName;
     });
     
     return coreData;
 }
 
 /*!
  *  @Author Dylan.
  *
  *  synthesize
  */
 @synthesize manageContext = _manageContext;
 @synthesize managedobjectModel = _managedobjectModel;
 @synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
 
 #pragma mark -
 #pragma mark - GET
 - (NSManagedObjectContext *)manageContext {
     
     if (_manageContext) {
         return _manageContext;
     }
     
     NSPersistentStoreCoordinator * coordinator = [self persistentStoreCoordinator];
     if (coordinator != nil) {
         _manageContext = [[NSManagedObjectContext alloc] init];
         [_manageContext setPersistentStoreCoordinator:coordinator];
     }
     return _manageContext;
 }
 
 - (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
     
     if (_persistentStoreCoordinator) {
         return _persistentStoreCoordinator;
     }
     
     NSURL * storeUrl = [[self applicationDomainUrl] URLByAppendingPathComponent:[NSString stringWithFormat:@"%@.sqlite", _storeName]];
     _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.managedobjectModel];
     [_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:nil];
     return _persistentStoreCoordinator;
 }
 
 - (NSManagedObjectModel *)managedobjectModel {
     
     if (_managedobjectModel) {
         return _managedobjectModel;
     }
     
     NSURL * modelUrl = [[NSBundle mainBundle] URLForResource:_storeName withExtension:@"momd"];
     _managedobjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelUrl];
     return _managedobjectModel;
 }
 
 #pragma mark - Methods
 - (NSMutableArray *)findByModel: (id)model {
     
     NSError * error = nil;
     NSArray * listArray = [_manageContext executeFetchRequest:[self bindRequest:CLASS_NAME(model) predicate:nil] error:&error];
     NSMutableArray * resultArray = [NSMutableArray array];
     
     for (ADCoreDataManager * manager in listArray) {
         
         for (NSString * propertyName in [self ClassAttributes:model]) {
             [model setValue:[manager valueForKey:propertyName] forKey:propertyName];
         }
         [resultArray addObject:model];
     }
     return resultArray;
 }
 
 - (NSMutableArray *)findByModel: (id)model
                 predicateString: (NSString *)predicateString; {
     
     NSError * error = nil;
     NSArray * listArray = [_manageContext executeFetchRequest:[self bindRequest:CLASS_NAME(model) predicate:predicateString] error:&error];
     NSMutableArray * resultArray = [NSMutableArray array];
     
     if (listArray.count >= 1) {
         for (ADCoreDataManager * manager in listArray) {
             
             for (NSString * propertyName in [self ClassAttributes:model]) {
                 [model setValue:[manager valueForKey:propertyName] forKey:propertyName];
             }
             [resultArray addObject:model];
         }
     }
     return resultArray;
 }
 
 #pragma mark update
 - (BOOL)create: (id)model {
     ADCoreDataManager * manager = [NSEntityDescription insertNewObjectForEntityForName:CLASS_NAME(model) inManagedObjectContext:_manageContext];
     
     for (NSString * propertyName in [self ClassAttributes:model]) {
         [manager setValue:[model valueForKey:propertyName] forKey:propertyName];
     }
     BOOL result = [self saveContext];
     return result;
 }
 
 - (BOOL)remove: (id)model {
     
     NSError * error = nil;
     NSArray * listArray = [_manageContext executeFetchRequest:[self bindRequest:CLASS_NAME(model) predicate:nil] error:&error];
     if (listArray.count > 0) {
         for (ADCoreDataManager * manager in listArray) {
             [_manageContext deleteObject:manager];
         }
     }
     return [self saveContext];
 }
 
 - (BOOL)remove: (id)model
 predicateString: (NSString *)predicateString {
     
     NSError * error = nil;
     NSArray * listArray = [_manageContext executeFetchRequest:[self bindRequest:CLASS_NAME(model) predicate:predicateString] error:&error];
     
     if (listArray.count > 0) {
         for (ADCoreDataManager * manager in listArray) {
             [_manageContext deleteObject:manager];
         }
     }
     return [self saveContext];
 }
 
 - (BOOL)modify: (id)model
  predicateString: (NSString *)predicateString {
     
     NSError * error = nil;
     NSArray * listArray = [_manageContext executeFetchRequest:[self bindRequest:CLASS_NAME(model) predicate:predicateString] error:&error];
     
     if (listArray.count > 0) {
         
         for (ADCoreDataManager * manager in listArray) {
             for (NSString * propertyName in [self ClassAttributes:model]) {
                 [manager setValue:[model valueForKey:propertyName] forKey:propertyName];
             }
         }
     }
     return [self saveContext];
 }
 
 #pragma mark - collect
 - (NSFetchRequest *)bindRequest: (NSString *)className
           predicate: (NSString *)predicateString {
     NSFetchRequest * request = [[NSFetchRequest alloc] init];
     [request setEntity:[NSEntityDescription entityForName:className inManagedObjectContext:_manageContext]];
     
     if (predicateString != nil) {
         NSPredicate * predicate = [NSPredicate predicateWithFormat:predicateString];
         NSLog(@"%@", predicate);
         NSLog(@"%@", predicateString);
         [request setPredicate:predicate];
     }
     return request;
 }
 
 
 #pragma mark - save
 - (BOOL)saveContext {
     
     NSManagedObjectContext * context = [self manageContext];
     if (context != nil) {
         
         NSError * error = nil;
         if ([context hasChanges] && ![context save:&error]) {
             NSLog(@"%@", [error userInfo]);
             abort();
             return NO;
         }
     }
     
     return YES;
 }
 
 
 - (NSURL *)applicationDomainUrl {
     return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
 }
 
 #pragma mark - allAttributes
 - (NSMutableArray *) ClassAttributes: (id)classModel {
     
     NSMutableArray * array = [NSMutableArray array];
     NSString *className = NSStringFromClass([classModel class]);
     const char * cClassName = [className UTF8String];
     
     id classM = objc_getClass(cClassName);
     unsigned int outCount, i;
     objc_property_t * properties = class_copyPropertyList(classM, &outCount);
     for (i = 0; i < outCount; i++) {
         objc_property_t property = properties[i];
         NSString * attributeName = [NSString stringWithUTF8String:property_getName(property)];
         
         [array addObject:attributeName];
     }
     return array;
 }
 
 @end

  在m文件中, 我使用了运行时。 运行时拿到一个模型的属性 这样我们可以更加方便的使用KVC

  大家仔细看一下这种封装的过程  

2.中间层: ADCoreDataManager.h

  

 //
 //  ADCoreDataManager.h
 //  CoreData_CE
 //
 //  Created by Dylan on 14-10-11.
 //  Copyright (c) 2014年 Dylan. All rights reserved.
 //
 
 #warning add Model properties Here
 
 #import <CoreData/CoreData.h>
 #import <Foundation/Foundation.h>
 
 @interface ADCoreDataManager : NSManagedObject
 
 /*!
  *  @Author Dylan.
  *
  *  e.g
  */
 @property (nonatomic, strong) NSString * name;
 
 @end

  .m文件

  

 //
 //  ADCoreDataManager.m
 //  CoreData_CE
 //
 //  Created by Dylan on 14-10-11.
 //  Copyright (c) 2014年 Dylan. All rights reserved.
 //
 
 #warning don't forget write @synthesize
 
 #import "ADCoreDataManager.h"
 
 @implementation ADCoreDataManager
 
 @synthesize name = _name;
 
 - (void)setValue:(id)value forUndefinedKey:(NSString *)key {
     
 }
 
 @end

  大家可以把所有模型的属性 扔到中间层里边。 使用中间层去做中介传值。

  使用:

  1. 创建自己的momd文件。 新建-》coredata-》model 创建之后添加模型

  2. 初始化单例

  附上测试代码

  

 // test
     ADCoreData * coreData = [ADCoreData shareInstanceWithStoreName:@"CoreData"];
     
     Dylan * dylan = [[Dylan alloc] initWithEntity:[NSEntityDescription entityForName:@"Dylan" inManagedObjectContext:coreData.manageContext] insertIntoManagedObjectContext:nil];
     [dylan setName:@"Dylan"];
     
     NSLog(@"**************************************************");
     
     NSLog(@"first = %@", [coreData findByModel:dylan]);
     
     NSLog(@"**************************************************");
     
     [coreData create:dylan];
     NSLog(@"second = %@", [coreData findByModel:dylan]);
     NSLog(@"third = %@", [coreData findByModel:dylan predicateString:@"name = 'Dylan'"]);
     NSLog(@"**************************************************");
     
     [coreData remove:dylan];
     NSLog(@"fourth = %@", [coreData findByModel:dylan]);
     NSLog(@"**************************************************");
     
     [coreData create:dylan];
     NSLog(@"fifth = %@", [coreData findByModel:dylan]);
     
     NSLog(@"**************************************************");
     
     Dylan * dylan1 = [[Dylan alloc] initWithEntity:[NSEntityDescription entityForName:@"Dylan" inManagedObjectContext:coreData.manageContext] insertIntoManagedObjectContext:nil];
     dylan1.name = @"dylan-1";
     
     [coreData modify:dylan1 predicateString:nil];
     NSLog(@"sixth = %@", [coreData findByModel:dylan]);
     NSLog(@"seventh = %@", [coreData findByModel:dylan1]);

  CoreData书写虽然比较难, 但是操作方便

  大家在使用谓词的时候 要特别的注意 在你的值上边加单引号 类似: name = 'Dylan' 防止CoreData在操作request请求时候出现错误

  @Dylan.



相关评论