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阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容

  • 注:本文来自Core Data by tutorials 2.0 , swift + iOS 9 .本文非翻译 只...
    smalldu阅读 879评论 3 5
  • 这两天深圳下大雨,看着公交车窗滑下的雨滴,又想起小时候。 农村的下雨天就是集体放假,关上门在阴暗的房间睡上长长的一...
    羊它它阅读 201评论 0 1
  • 你怎么对我,我就怎么对你。说实话,我真的心眼很小。对于其他人,基本上就没几个能入我眼的,当然,我也不入他们的眼。大...
    thanksgi阅读 121评论 0 0
  • 人在心情好的时候做任何事都是带有幸福感的,并且不会很累。今天的充实的学习生活让我对接下来的计划有了积极的盼望。不过...
    木易小王爷阅读 207评论 0 0