Core Data數(shù)據(jù)持久化存儲

1.Core Data 含義:

Core Data(數(shù)據(jù)庫)是數(shù)據(jù)持久化存儲的最適合的方式,通過一系列特性避免使用SQL的一些麻煩咧织,還能合理管理內(nèi)存。

Core Data是iOS5之后才出現(xiàn)的一個框架籍救。

它提供了對象-關(guān)系映射(ORM)的功能习绢,即能夠?qū)C對象轉(zhuǎn)化成數(shù)據(jù),保存在SQLite數(shù)據(jù)庫文件中蝙昙,也能夠?qū)⒈4嬖跀?shù)據(jù)庫中的數(shù)據(jù)還原成OC對象毯炮。

在此數(shù)據(jù)操作期間,我們不需要編寫任何SQL語句耸黑,這個有點類似于著名的Hibernate持久化框架桃煎,不過功能肯定是沒有Hibernate強大的。


2.Core Data 優(yōu)點:

利用Core Data框架大刊,我們就可以輕松地將數(shù)據(jù)庫里面的2條記錄轉(zhuǎn)換成2個OC對象为迈,也可以輕松地將2個OC對象保存到數(shù)據(jù)庫中,變成2條表記錄缺菌,而且不用寫一條SQL語句葫辐。

在Core Data,需要進行映射的對象稱為實體(entity)伴郁,而且需要使用Core Data的模型文件來描述app中的所有實體和實體屬性耿战。


3.Core Data 支持的存儲類型:

SQLite、內(nèi)存焊傅、二進制剂陡、XML、自定義數(shù)據(jù)類型


4.Core Data 的使用:

例子:對用戶輸入的信息放入數(shù)據(jù)庫狐胎,可對數(shù)據(jù)進行保存鸭栖、刪除、查看

創(chuàng)建工程時握巢,勾選Use Core Data選項

||

創(chuàng)建工程后晕鹊,增加Xcode數(shù)據(jù)模型文件

||

AppDelegate.h文件中,自動生成

方法saveContext表示:保存數(shù)據(jù)到數(shù)據(jù)庫。
方法applicationDocumentsDirectory表示:應(yīng)用程序沙盒下的Documents目錄路徑溅话。

||

建表晓锻、設(shè)置字段名、建立的表就是一個對象

||

NSManagedObject為每張表新建類(Xcode 8 更改了生成地方)
簡單了解NSManagedObject:

1.通過Core Data從數(shù)據(jù)庫取出的對象飞几,默認情況下都是NSManagedObject對象带射。

2.NSManagedObject的工作模式有點類似于NSDictionary對象,通過鍵-值對來存取所有的實體屬性:
1> setValue:forKey:存儲屬性值(屬性名為key)
2> valueForKey:獲取屬性值(屬性名為key)

||

選擇數(shù)據(jù)庫

||

選擇表

||

生成這幾個文件對應(yīng)相應(yīng)的數(shù)據(jù)庫循狰,Contactinformation+CoreDataProperties是分類

||

Contactinformation.h文件Demo:

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h> //導(dǎo)入分類

NS_ASSUME_NONNULL_BEGIN

@interface Contactinformation : NSManagedObject
//返回實體名(類名)
+ (NSString *)entityName;
@end

NS_ASSUME_NONNULL_END

#import "Contactinformation+CoreDataProperties.h"

||

Contactinformation.m文件Demo:

#import "Contactinformation.h"

@implementation Contactinformation
+ (NSString *)entityName{
    return @"Contactinformation";
}

//重寫description
- (NSString *)description{
    return [NSString stringWithFormat:@"<name = %@, age = %@, sex = %@, telephone = %@, birthday = %@, adress = %@>",self.name,self.age,self.sex,self.telephone,self.birthday,self.adress];
}
@end

||
####### 封裝保存窟社、插入、刪除數(shù)據(jù)庫的數(shù)據(jù)方法
CoreDataManager.h文件的Demo

//封裝保存绪钥、插入灿里、刪除數(shù)據(jù)庫數(shù)據(jù)
#import <Foundation/Foundation.h>

@interface CoreDataManager : NSObject
//插入
+ (BOOL)insertObjectWithParameter:(NSDictionary *)parameters entityName:(NSString *)entityName;
//查詢
+ (NSArray *)readentityName:(NSString *)entityName predicate:(NSString *)predicateString;
//刪除
+ (BOOL)removeWithEntityName:(NSString *)entityName predicate:(NSString *)predicateString;
@end

CoreDataManager.m文件的Demo

#import "CoreDataManager.h"
#import "AppDelegate.h"
@implementation CoreDataManager

//委托對象上下文方法
+ (NSManagedObjectContext *)managedObjectContext{
    //獲取程序唯一的委托對象上下文,用于存儲程腹、查詢匣吊、刪除
    return [(AppDelegate *)[UIApplication sharedApplication].delegate managedObjectContext];
}

//插入
+ (BOOL)insertObjectWithParameter:(NSDictionary *)parameters entityName:(NSString *)entityName{
    if (entityName.length == 0) { //異常情況判斷
        return nil;
    }
    //獲取數(shù)據(jù)(已存在parameters對象中)
    //用實體名實例化模型對象
    NSManagedObject *contect = [NSEntityDescription insertNewObjectForEntityForName:entityName inManagedObjectContext:[self managedObjectContext]]; //用NSManagedObject父類接收
    //把數(shù)據(jù)存入實體對象
    for (NSString *key in parameters) {
        //KVC (建立的值一樣才能用KVC)
        [contect setValue:parameters[key] forKey:key];
    }
    //保存同步文件
    BOOL success = [[self managedObjectContext] save:nil];
    NSLog(@"是否保存成功:%d",success);
    return success;
}
//查詢
+ (NSArray *)readentityName:(NSString *)entityName predicate:(NSString *)predicateString{
    if (entityName.length == 0) { //異常情況判斷
        return nil;
    }
    //1.實例化查詢請求類
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:entityName];
    //2.配置查詢條件(可選操作)
    if (predicateString.length > 0) {
        fetchRequest.predicate = [NSPredicate predicateWithFormat:predicateString]; //年齡等于6才能保存
    }
    //3.執(zhí)行查詢
    NSArray *results = [[self managedObjectContext] executeFetchRequest:fetchRequest error:nil];
    NSLog(@"results = %@",results);
    return results;
}
//刪除
+ (BOOL)removeWithEntityName:(NSString *)entityName predicate:(NSString *)predicateString{
    if (entityName.length == 0) { //異常情況判斷
        return nil;
    }
    NSArray *results = [self readentityName:entityName predicate:predicateString]; //調(diào)用查詢數(shù)據(jù)庫方法 //1.2.3.步驟在查詢數(shù)據(jù)庫方法中
    //4.數(shù)據(jù)對象的刪除 (從數(shù)據(jù)庫中刪除)
    for (id object in results) { //所有數(shù)據(jù)
        [[self managedObjectContext] deleteObject:object];
    }
    //5.保存同步數(shù)據(jù)
    BOOL success = [[self managedObjectContext] save:nil];
    NSLog(@"是否刪除成功:%d",success);
    return success;
}
@end

||

下面ViewController.m文件是關(guān)于iOS界面與如何使用數(shù)據(jù)庫的Demo
#import "ViewController.h"
#import "Contactinformation.h"
#import "AppDelegate.h"
#import "CoreDataManager.h"

static const NSInteger TEXTFIELD_BASE_TAG = 20;

@interface ViewController ()
@property (nonatomic, strong) NSArray *keys;
@end

@implementation ViewController{
    //聲明變量
    //委托對象上下文
    NSManagedObjectContext *_context;
}

//初始化
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self) {
        //獲取程序唯一的委托對象上下文,用于存儲寸潦、查詢色鸳、刪除
        _context = [(AppDelegate *)[UIApplication sharedApplication].delegate managedObjectContext]; //有一個強轉(zhuǎn)否則不認識 //獲取程序單例(唯一)
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _keys = @[@"adress",@"name",@"age",@"sex",@"telephone",@"birthday"];
    for (int i = 0; i < 6; i ++) {
        UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(30, (20 + 30 * i) * 2, 100, 30)];
        label1.text = [_keys[i] stringByAppendingString:@":"];
        label1.textAlignment = NSTextAlignmentRight;
        [self.view addSubview:label1];

        UITextField *text = [[UITextField alloc] initWithFrame:CGRectMake(140, (20 + 30 * i) * 2, 200, 30)];
        text.backgroundColor = [UIColor whiteColor];
        text.layer.borderColor = [UIColor grayColor].CGColor;
        text.layer.borderWidth = 1;
        text.tag = TEXTFIELD_BASE_TAG + i;
        text.layer.cornerRadius = 8;
        [self.view addSubview:text];
    }
    NSArray *array1 = @[@"save",@"read",@"clear"];
    for (int i = 0; i < 3; i ++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake((30 * i + 20) * 3, 400, 50, 30);
        button.backgroundColor = [UIColor clearColor];
        [button setTitle:array1[i] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:18];
        button.tag = 100 + i;
        [button addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
    }
}


- (void)button:(UIButton *)sender{
    if (sender.tag == 100) {
        [self insertContext];
    }else if (sender.tag == 101){
        [self readContext];
    }else{
        [self clearContext];
    }
}

//插入
- (void)insertContext{
    
    //采用封裝
    [CoreDataManager insertObjectWithParameter:[self contactInformation] entityName:[Contactinformation entityName]];
}

//查詢
- (void)readContext{
    
    //采用封裝
    [CoreDataManager readentityName:[Contactinformation entityName] predicate:nil];
}

//刪除
- (void)clearContext{
    
    //采用封裝
    [CoreDataManager removeWithEntityName:[Contactinformation entityName] predicate:nil];
}

//文本框內(nèi)容獲取方法
- (NSDictionary *)contactInformation{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    for (NSInteger i = 0; i < _keys.count; i ++) {
        UITextField *field = (UITextField *)[self.view viewWithTag:TEXTFIELD_BASE_TAG + i];
        if (field.text.length > 0) {
            [dic setObject:field.text forKey:_keys[i]];
        }
    }
    return dic;
}
@end
例子演示結(jié)果:
結(jié)果演示

Core Data中的核心對象

3098145-36fded7ab59714e8.png.jpeg
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市见转,隨后出現(xiàn)的幾起案子命雀,更是在濱河造成了極大的恐慌,老刑警劉巖斩箫,帶你破解...
    沈念sama閱讀 219,270評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件吏砂,死亡現(xiàn)場離奇詭異,居然都是意外死亡乘客,警方通過查閱死者的電腦和手機狐血,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,489評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來易核,“玉大人匈织,你說我怎么就攤上這事∧抵保” “怎么了缀匕?”我有些...
    開封第一講書人閱讀 165,630評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長井氢。 經(jīng)常有香客問我弦追,道長岳链,這世上最難降的妖魔是什么花竞? 我笑而不...
    開封第一講書人閱讀 58,906評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上约急,老公的妹妹穿的比我還像新娘零远。我一直安慰自己,他們只是感情好厌蔽,可當我...
    茶點故事閱讀 67,928評論 6 392
  • 文/花漫 我一把揭開白布牵辣。 她就那樣靜靜地躺著,像睡著了一般奴饮。 火紅的嫁衣襯著肌膚如雪纬向。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,718評論 1 305
  • 那天戴卜,我揣著相機與錄音逾条,去河邊找鬼。 笑死投剥,一個胖子當著我的面吹牛师脂,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播江锨,決...
    沈念sama閱讀 40,442評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼吃警,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了啄育?” 一聲冷哼從身側(cè)響起酌心,我...
    開封第一講書人閱讀 39,345評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎挑豌,沒想到半個月后谒府,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,802評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡浮毯,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,984評論 3 337
  • 正文 我和宋清朗相戀三年完疫,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片债蓝。...
    茶點故事閱讀 40,117評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡壳鹤,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出饰迹,到底是詐尸還是另有隱情芳誓,我是刑警寧澤,帶...
    沈念sama閱讀 35,810評論 5 346
  • 正文 年R本政府宣布啊鸭,位于F島的核電站锹淌,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏赠制。R本人自食惡果不足惜赂摆,卻給世界環(huán)境...
    茶點故事閱讀 41,462評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧烟号,春花似錦绊谭、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,011評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至迫筑,卻和暖如春宪赶,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背脯燃。 一陣腳步聲響...
    開封第一講書人閱讀 33,139評論 1 272
  • 我被黑心中介騙來泰國打工逊朽, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人曲伊。 一個月前我還...
    沈念sama閱讀 48,377評論 3 373
  • 正文 我出身青樓叽讳,卻偏偏與公主長得像,于是被迫代替她去往敵國和親坟募。 傳聞我的和親對象是個殘疾皇子岛蚤,可洞房花燭夜當晚...
    茶點故事閱讀 45,060評論 2 355

推薦閱讀更多精彩內(nèi)容

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件懈糯、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 12,107評論 4 62
  • 簡介 Core Data是一個功能強大的對象數(shù)據(jù)庫涤妒,提供了強大的數(shù)據(jù)存儲管理功能。它提供的對象-關(guān)系映射功能赚哗,能夠...
    阿道道閱讀 1,016評論 0 0
  • 適讀對象: 需要入門Core Data的朋友她紫; 像我一樣,尚未學(xué)過數(shù)據(jù)庫相關(guān)課程屿储,不太懂怎么寫SQLite語句的朋...
    AntonyWong閱讀 5,212評論 8 21
  • 凌晨一點贿讹,這是我最想注冊的昵稱,可是已經(jīng)被別人注冊了够掠。不只是哪個半夜沒睡覺的家伙民褂,跟我一樣心血來潮,想寫點兒什么吧...
    午夜一點閱讀 235評論 0 1
  • 白天的時間還能逃 可漆黑的夜要怎么忘掉 我聽見孤單 在寒風(fēng)中呼嘯 我聽見嘶吼 這猙獰的猛獸 ??
    蒼軒客閱讀 128評論 0 0