數(shù)據(jù)庫-CoreData簡介 - (Obj-C)

Core Data 是iOS SDK里的一個(gè)很強(qiáng)大的框架,允許程序員以面向?qū)ο蟮姆绞絻?chǔ)存和管理數(shù)據(jù).使用Core Data框架,可以很輕松有效的通過面向?qū)ο蟮慕涌诠芾頂?shù)據(jù)

Core Data框架提供了對(duì)象-關(guān)系映射(ORM)的功能,即能夠?qū)C對(duì)象轉(zhuǎn)化成數(shù)據(jù),保存在SQLite3數(shù)據(jù)庫文件中,也能夠?qū)⒈4嬖跀?shù)據(jù)庫中的數(shù)據(jù)還原成OC對(duì)象

和SQLite的區(qū)別:Core Data不支持SQL語句
Core Data是對(duì)SQLite3的封裝,底層還是SQL語句,在數(shù)據(jù)操作過程中,將數(shù)據(jù)關(guān)系映射成對(duì)象,直接操作對(duì)象

SQL數(shù)據(jù)庫中的三個(gè)核心元素:表、字段大莫、記錄(一條數(shù)據(jù))
Core Data中與表對(duì)應(yīng)的叫做實(shí)體(Entity),實(shí)體在模型文件(DataModel)中設(shè)置數(shù)據(jù)的映射關(guān)系
Core Data中與字段對(duì)應(yīng)的是屬性(Attribute),屬性在實(shí)體中設(shè)置
Core Data中與記錄對(duì)應(yīng)的是對(duì)象(基類NSManagedObject),對(duì)象根據(jù)實(shí)體生成,CoreData通過操作對(duì)象進(jìn)行數(shù)據(jù)存儲(chǔ)

創(chuàng)建工程時(shí),直接勾選Use Core Data,這樣創(chuàng)建工程時(shí)自動(dòng)集成了Core Data

CoreData_1.png

與普通創(chuàng)建工程的區(qū)別在于,勾選Use Core Data創(chuàng)建好的工程,會(huì)多出一個(gè)文件:

工程名.xcdatamodeld

CoreData_2.png

點(diǎn)擊下面的Add Entity,創(chuàng)建實(shí)體
添加Entity(創(chuàng)建表)
添加Attributes(添加字段)

CoreData_3.png

并且在Appdelegate中,也默認(rèn)幫我們實(shí)現(xiàn)了部分功能:
.h中

#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
// 數(shù)據(jù)上下文  直接負(fù)責(zé)數(shù)據(jù)的增刪改查
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
// 數(shù)據(jù)模型 對(duì)應(yīng)的數(shù)據(jù)模型文件(.xcdatamodeld)
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
// 持久化存儲(chǔ)協(xié)調(diào)器
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;

// 保存上下文   增刪改查后,必須保存上下文,持久化協(xié)調(diào)器才會(huì)將數(shù)據(jù)和數(shù)據(jù)庫同步
- (void)saveContext;
// 沙盒Documents路徑    CoreData生成的數(shù)據(jù)庫默認(rèn)就在Documents中
- (NSURL *)applicationDocumentsDirectory;

@end

.m中


#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "---ShenYJ---._1_Core_Data" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"_1_Core_Data" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"_1_Core_Data.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末烈炭,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子优妙,更是在濱河造成了極大的恐慌乘综,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,525評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件套硼,死亡現(xiàn)場(chǎng)離奇詭異卡辰,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)邪意,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,203評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門九妈,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人雾鬼,你說我怎么就攤上這事萌朱。” “怎么了呆贿?”我有些...
    開封第一講書人閱讀 164,862評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵嚷兔,是天一觀的道長森渐。 經(jīng)常有香客問我,道長冒晰,這世上最難降的妖魔是什么同衣? 我笑而不...
    開封第一講書人閱讀 58,728評(píng)論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮壶运,結(jié)果婚禮上耐齐,老公的妹妹穿的比我還像新娘。我一直安慰自己蒋情,他們只是感情好埠况,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,743評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著棵癣,像睡著了一般辕翰。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上狈谊,一...
    開封第一講書人閱讀 51,590評(píng)論 1 305
  • 那天喜命,我揣著相機(jī)與錄音,去河邊找鬼河劝。 笑死壁榕,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的赎瞎。 我是一名探鬼主播牌里,決...
    沈念sama閱讀 40,330評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼务甥!你這毒婦竟也來了牡辽?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,244評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤缓呛,失蹤者是張志新(化名)和其女友劉穎催享,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體哟绊,經(jīng)...
    沈念sama閱讀 45,693評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡因妙,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,885評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了票髓。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片攀涵。...
    茶點(diǎn)故事閱讀 40,001評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖洽沟,靈堂內(nèi)的尸體忽然破棺而出以故,到底是詐尸還是另有隱情,我是刑警寧澤裆操,帶...
    沈念sama閱讀 35,723評(píng)論 5 346
  • 正文 年R本政府宣布怒详,位于F島的核電站炉媒,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏昆烁。R本人自食惡果不足惜吊骤,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,343評(píng)論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望静尼。 院中可真熱鬧白粉,春花似錦、人聲如沸鼠渺。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,919評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽拦盹。三九已至鹃祖,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間普舆,已是汗流浹背惯豆。 一陣腳步聲響...
    開封第一講書人閱讀 33,042評(píng)論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留奔害,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,191評(píng)論 3 370
  • 正文 我出身青樓地熄,卻偏偏與公主長得像华临,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子端考,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,955評(píng)論 2 355

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

  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法雅潭,類相關(guān)的語法,內(nèi)部類的語法却特,繼承相關(guān)的語法扶供,異常的語法,線程的語...
    子非魚_t_閱讀 31,633評(píng)論 18 399
  • 1.CoreData 1.1 CoreData概述 1)Core data 是數(shù)據(jù)持久存儲(chǔ)的最佳方式 2)Core...
    微春風(fēng)閱讀 3,816評(píng)論 0 10
  • 早上起來習(xí)慣性的去網(wǎng)上瀏覽一番仙蛉,無意中發(fā)現(xiàn)一篇以前轉(zhuǎn)載過的一篇帖子《27歲建筑師之死》笋敞,說的是一位看似前途似錦...
    姜三瘋閱讀 615評(píng)論 0 49
  • 我很想推心置腹的說一些話,但結(jié)果往往都成了自己說給自己聽荠瘪。 我曾經(jīng)結(jié)識(shí)過很多人夯巷,一起把酒言歡赛惩,笑談人生,但往往都成...
    瘦肉小哥閱讀 350評(píng)論 0 2
  • 我像平時(shí)一樣的到面館去吃面條趁餐,純粹就是民工飯店喷兼。我下班后走入飯店,已經(jīng)有很多民工把5張桌子坐滿了澎怒。 我坐在他們的對(duì)...
    高安讓閱讀 650評(píng)論 9 13