iOS_SN_CoreDate(一)封裝使用

 

看過一篇封裝CoreData的文章挺不錯,有基本使用封裝,可是沒有寫怎麼與tableView結合使用,我本身用的過程有些小波折,本身作了一個demo,你們能夠看源碼一些基本使用應該不難了,git

 

原文:http://blog.csdn.net/pengyuan_d/article/details/40657225?utm_source=tuicool&utm_medium=referralgithub

(1)建立一個Data Model文件,命名爲MyModel.xcdatamodeldsql

(2)建立Users表,添加如圖的字段數組

(3)建立NSManagedObject subclass表實體文件ide

(4)在Users.m文件中,覆寫description方法ui

 

CoreDataDBHelper.h

 

#import <Foundation/Foundation.h>  
#import <CoreData/CoreData.h>  
  
// 本地文件存儲的路徑  
#define PATH [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/sqlite.db"]  
  
#define MODEL_NAME @"MyModel"  
  
@interface CoreDataDBHelper : NSObject  
{  
    // 1.數據模型對象  
    NSManagedObjectModel *_managedObjectModel;  
      
    // 2.建立本地持久文件對象  
    NSPersistentStoreCoordinator *_persistentStoreCoordinator;  
      
    // 3.管理數據對象  
    NSManagedObjectContext *_managedObjectContext;  
}  
  
// 設計成單例模式  
+ (CoreDataDBHelper *)shareCoreDataDBHelper;  
  
// 添加數據的方法  
- (BOOL)insertDataWithModelName:(NSString *)modelName  
          setAttributWithDic:(NSDictionary *)params;  
  
// 查看  
/* 
    modelName           :實體對象類的名字 
    predicateString     :謂詞條件 
    identifers          :排序字段集合 
    ascending           :是否升序 
 */  
- (NSArray *)selectDataWithModelName:(NSString *)modelName  
                     predicateString:(NSString *)predicateString  
                                sort:(NSArray *)identifers  
                           ascending:(BOOL)ascending;  
  
// 修改  
- (BOOL)updateDataWithModelName:(NSString *)modelName  
                predicateString:(NSString *)predicateString  
             setAttributWithDic:(NSDictionary *)params;  
  
// 刪除  
- (BOOL)deleteDataWithModelName:(NSString *)modelName  
                predicateString:(NSString *)predicateString;  
  
@end  

CoreDataDBHelper.mspa

  

#import "CoreDataDBHelper.h"  
  
@implementation CoreDataDBHelper  
  
- (instancetype)init  
{  
    self = [super init];  
    if (self)  
    {  
        // 1.數據模型對象  
        NSURL *modelUrl = [[NSBundle mainBundle] URLForResource:MODEL_NAME withExtension:@"momd"];  
        _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelUrl];  
          
        // 2.建立本地持久文件對象  
        _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:_managedObjectModel];  
        // 設置本地數據的保存位置  
        NSURL *fileUrl = [NSURL fileURLWithPath:PATH];  
          
        [_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:fileUrl options:nil error:nil];  
          
        // 3.管理數據對象  
        _managedObjectContext = [[NSManagedObjectContext alloc] init];  
        [_managedObjectContext setPersistentStoreCoordinator:_persistentStoreCoordinator];  
    }  
    return self;  
}  
  
  
// 設計成單例模式  
+ (CoreDataDBHelper *)shareCoreDataDBHelper  
{  
    static CoreDataDBHelper *coreDataDBHelper = nil;  
    static dispatch_once_t onceToken;  
    dispatch_once(&onceToken, ^{  
        coreDataDBHelper = [[CoreDataDBHelper alloc] init];  
    });  
      
    return coreDataDBHelper;  
}  
  
// 添加數據的方法  
/* 
    params : @{  
                  @"name":@"張三", 
                  @"age":@20 
             } 
 */  
- (BOOL)insertDataWithModelName:(NSString *)modelName  
             setAttributWithDic:(NSDictionary *)params  
{  
    NSEntityDescription *entity = [NSEntityDescription insertNewObjectForEntityForName:modelName inManagedObjectContext:_managedObjectContext];  
      
    // 遍歷參數字典  
    for (NSString *key in params)  
    {  
        SEL selector = [self selWithKeyName:key];  
        if ([entity respondsToSelector:selector])  
        {  
            [entity performSelector:selector withObject:params[key]];  
        }  
    }  
    [_managedObjectContext insertObject:entity];  
      
    // 保存到本地  
    return [_managedObjectContext save:nil];  
}  
  
// 查看  
/* 
 modelName           :實體對象類的名字 
 predicateString     :謂詞條件 
 identifers          :排序字段集合 
 ascending           :是否升序 
 */  
- (NSArray *)selectDataWithModelName:(NSString *)modelName  
                     predicateString:(NSString *)predicateString  
                                sort:(NSArray *)identifers  
                           ascending:(BOOL)ascending  
{  
    // 1.建立實體對象  
    NSEntityDescription *entity = [NSEntityDescription entityForName:modelName inManagedObjectContext:_managedObjectContext];  
      
    // 2.建立一個查詢對象  
    NSFetchRequest *request = [[NSFetchRequest alloc] init];  
    // 告訴查詢對象你要查詢的數據類型  
    [request setEntity:entity];  
      
    // 添加查詢條件  
    if (predicateString != nil || [predicateString isEqualToString:@""])  
    {  
        NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateString];  
        [request setPredicate:predicate];  
    }  
      
      
    // 3.設置排序  
    NSMutableArray *sortDescriptors = [NSMutableArray array];  
    for (NSString *identifer in identifers)  
    {  
        // 建立排序對象  
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:identifer ascending:ascending];  
        // 把排序對象添加到數組中  
        [sortDescriptors addObject:sortDescriptor];  
    }  
    // 把排序對象設置到查詢對象裏面  
    [request setSortDescriptors:sortDescriptors];  
      
    // 3.開始查詢  
    return [_managedObjectContext executeFetchRequest:request error:nil];  
}  
  
  
// 修改  
- (BOOL)updateDataWithModelName:(NSString *)modelName  
                predicateString:(NSString *)predicateString  
             setAttributWithDic:(NSDictionary *)params  
{  
    // 獲取全部須要修改實體對象  
    NSArray *entitys = [self selectDataWithModelName:modelName predicateString:predicateString sort:nil ascending:NO];  
      
    // 遍歷全部的實體對象  
    for (NSEntityDescription *entity in entitys)  
    {  
        // 修改對象的屬性  
        for (NSString *key in params)  
        {  
            SEL selector = [self selWithKeyName:key];  
            if ([entity respondsToSelector:selector])  
            {  
                [entity performSelector:selector withObject:params[key]];  
            }  
        }  
    }  
      
    return [_managedObjectContext save:nil];  
      
}  
  
// 刪除  
- (BOOL)deleteDataWithModelName:(NSString *)modelName  
                predicateString:(NSString *)predicateString  
{  
    // 獲取全部須要修改實體對象  
    NSArray *entitys = [self selectDataWithModelName:modelName predicateString:predicateString sort:nil ascending:NO];  
      
    // 遍歷全部的實體對象  
    for (NSEntityDescription *entity in entitys)  
    {  
        // 刪除對象  
        [_managedObjectContext deleteObject:entity];  
          
    }  
      
    return [_managedObjectContext save:nil];  
}  
  
  
// 經過一個字符串反回一個set方法  
- (SEL)selWithKeyName:(NSString *)keyName  
{  
    NSString *first = [[keyName substringToIndex:1] uppercaseString];  
    NSString *end = [keyName substringFromIndex:1];  
    NSString *selString = [NSString stringWithFormat:@"set%@%@:",first,end];  
    return NSSelectorFromString(selString);  
}  
  
@end  

本文GitHub地址https://github.com/zhangkiwi/iOS_SN_CoreData.net

相關文章
相關標籤/搜索