Core Data學習筆記一:創建CoreDataStack

iOS 10 以前創建CoreDataStack


1 Data Model

Data Model 是Xcode提供的一個可視化Model 編輯器,可以創建實例,定義實例屬性,定義實例之間的關系,以及創建一些常用的FetchRequst

1.1 新建DataModel 文件
1.png
1.2 添加實例&定義屬性
2.png
1.21 屬性類型(Attribute Type)
  • Integer16 Integer32 Integer64
  • Decimal Float Double
  • String
  • Boolean
  • Date
  • Binary Data
  • Transformable

其中,Binary Data 為二進制數據,在Xcode右側Model Inspector 中,有一個可以設置Allows External Storage的選項,CoreData會智能選擇是存儲文件的二進制數據,還是存儲文件URL

Transformable 可以為任意遵循NSCoding協議的對象類型

1.3 添加關系(relationShip)
  • to one (一對一)
  • to Manay (一對多)

這里再定義一個實例,主人(master),設定主人和狗子的關系為一對多,關系圖如下:

3.png

2 CoreDataStack

CoreDataStck,是自定義的一個CoreData 的棧對象,為一個單例,可以通過它,初始化項目的CoreData,以及獲取到Context,對數據庫進行增刪改查等操作

2.1 單例
//  CoreDataStack.h

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

@interface CoreDataStack : NSObject

+ (instancetype)sharedInstance;

@end
//  CoreDataStack.m

#import "CoreDataStack.h"

@implementation CoreDataStack

+ (instancetype)sharedInstance {
    static CoreDataStack *stack;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        stack = [[CoreDataStack alloc] init];
    });
    
    return stack;
}
@end

3 NSManagedModel

The NSManagedObjectModel represents each object type in your app's data model, the properties they can have, and the relationship between them.

//  CoreDataStack.m

@interface CoreDataStack ()

@property (nonatomic, strong) NSManagedObjectModel *managedModel;

@end

......
- (NSManagedObjectModel *)managedModel {
    if (!_managedModel) {
        NSURL *momdURL = [[NSBundle mainBundle]URLForResource:@"Model" withExtension:@"momd"];
        _managedModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:momdURL];
    }
    return _managedModel;
}

NSManagedObjectModel通過Xcode創建的DataModel文件初始化,DataModel文件編譯后的后綴為momd

4 NSPersistentStoreCoordinator

4.1 NSpersistentStore
atomic vs nonatomic

An atomic persistent store needs to be completely deserialized and loaded into memory before you can make any read or write operations. In contrast, a non- atomic persistent store can load chunks of itself onto memory as needed.

type
  • NSSQLiteStoreType (nonatomic)
  • NSXMLStoreType (atomic)
  • NSBinaryStoreType (atomic)
  • NSInMemoryStoreType (atomic)

4.2 NSPersistentStoreCoordinator

the bridge between the managed object model and the persistent store

  • 通過managed object model初始化
  • 通過addPersistentStoreWithType:configuration:URL:options:error: 添加persistent store
//  CoreDataStack.m

@interface CoreDataStack ()

@property (nonatomic, strong) NSPersistentStoreCoordinator *psc;

@end

......

- (NSPersistentStoreCoordinator *)psc {
    if (!_psc) {
        _psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.managedModel];
        
        NSURL *URL = [[self documentURL] URLByAppendingPathComponent:@"Model.sqlite"];
        NSError *error;
        if (![_psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:URL options:nil error:&error]) {
            NSLog(@"addPersistentStoreWithType Error: %@",[error localizedDescription]);
        }
    }
    return _psc;
}

- (NSURL *)documentURL {
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];
}

5 NSManagedObjectContext

Context是唯一暴露給外界,供外界使用的接口

  • context an in-memory scratchpad for managed objects.
  • any change you make won't affect the underlying data on disk until you call -save: of context
  • context manages the lifecycle of the objects that it creates or fetches.
  • A managed object cannot exist without an associated context.
  • once a managed object has associated with a particular context, it will remain associated with the same context for the duration of its lifecycle.
  • context and managed object is not thread safe
//  CoreDataStack.h

@interface CoreDataStack : NSObject

@property (nonatomic, strong, readonly) NSManagedObjectContext *managedContext;

@end

//  CoreDataStack.m

@interface CoreDataStack ()

@property (nonatomic, strong, readwrite) NSManagedObjectContext *managedContext;

@end

- (NSManagedObjectContext *)managedContext {
    if (!_managedContext) {
        _managedContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
        _managedContext.persistentStoreCoordinator = self.psc;
    }
    return _managedContext;
}


6 Save Context

- (void)saveContext {
    NSError *error;
    if ([self.managedContext hasChanges] && ![self.managedContext save:&error]) {
        NSLog(@"NSManagedObjectContext Save Error: %@",[error localizedDescription]);
    }
}

iOS 10 以后創建CoreDataStack


iOS 10 以后,蘋果系統為我們封裝了一個CoreData Stack 的類,叫NSPersistentContainer,可以通過它的屬性viewContext獲取到NSManagedObjectContext

@property (readonly, strong) NSPersistentContainer *persistentContainer;

- (NSPersistentContainer *)persistentContainer {
    // The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
    @synchronized (self) {
        if (_persistentContainer == nil) {
            _persistentContainer = [[NSPersistentContainer alloc] initWithName:@"testCoreData"];
            [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
                if (error != nil) {
                    // 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.
                    
                    /*
                     Typical reasons for an error here include:
                     * The parent directory does not exist, cannot be created, or disallows writing.
                     * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                     * The device is out of space.
                     * The store could not be migrated to the current model version.
                     Check the error message to determine what the actual problem was.
                    */
                    NSLog(@"Unresolved error %@, %@", error, error.userInfo);
                    abort();
                }
            }];
        }
    }
    
    return _persistentContainer;
}

- (void)saveContext {
    NSManagedObjectContext *context = self.persistentContainer.viewContext;
    NSError *error = nil;
    if ([context hasChanges] && ![context 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();
    }
}

源碼下載


https://github.com/mengtian-li/CoreDataStackDemo/releases/tag/v0.1

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,362評論 6 537
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,013評論 3 423
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,346評論 0 382
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,421評論 1 316
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,146評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,534評論 1 325
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,585評論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,767評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,318評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,074評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,258評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,828評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,486評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,916評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,156評論 1 290
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,993評論 3 395
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,234評論 2 375

推薦閱讀更多精彩內容

  • 注:本文來自Core Data by tutorials 2.0 , swift + iOS 9 .本文非翻譯 只...
    smalldu閱讀 899評論 3 5
  • 這兩天深圳下大雨,看著公交車窗滑下的雨滴,又想起小時候。 農村的下雨天就是集體放假,關上門在陰暗的房間睡上長長的一...
    羊它它閱讀 212評論 0 1
  • 你怎么對我,我就怎么對你。說實話,我真的心眼很小。對于其他人,基本上就沒幾個能入我眼的,當然,我也不入他們的眼。大...
    thanksgi閱讀 128評論 0 0
  • 人在心情好的時候做任何事都是帶有幸福感的,并且不會很累。今天的充實的學習生活讓我對接下來的計劃有了積極的盼望。不過...
    木易小王爺閱讀 222評論 0 0