你好,歡迎來到IOS教程網

 Ios教程網 >> IOS使用技巧 >> IOS技巧綜合 >> CoreData教學完整版(封裝我們自己的CoreData工具)_Dylan

CoreData教學完整版(封裝我們自己的CoreData工具)_Dylan

編輯:IOS技巧綜合
[摘要]本文是對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.

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved