18.0~18.10 Core Data

本文详细介绍了Core Data的使用,包括核心概念如Persistent Store、Managed Object Context和数据模型,以及如何创建数据模型、生成类文件、保存和读取数据。此外,还讲解了后台数据的异步获取和自定义数据类型的应用。
摘要由CSDN通过智能技术生成

18.0. IntroductionCore Data

core data 是一个很强大的框架,它使得程序员能够以对象的形式保存和管理对象。传统做法,程序员只能使用oc自带的归档能力保存数据,或是手动写入数据。利用core data,programer可以更有效的管理数据。

core data 隐藏了底层的实现细节。programer只需要知道它提供的api。不过理解core data的结构,以及其工作原理很重要。

使用新的llvm编译器时,你只需引入头文件

#import <CoreData/CoreData.h>


首先需要了解一下概念

Persistent store:磁盘上代表实际数据的对象,我们不直接使用这个对象

Persistent store coordinator:从Persistent store 中读取和写入信息的协调员。是连接managed object context

Persistent store 的桥梁

Managed object model (MOM):磁盘上的代表数据模型的文件。类似数据库架构的东西

Managed object:保存core data的入口类。对应传统的数据库上的表。NSManagedObject类型。其实例都在managed object contexts上,通过persistent store coordinator才能保存到persistent store

Managed object context (MOC):这是一块虚拟的板,奇怪吧,我们在内存中创建core data 对象并设置属性。这些工作都是在MOC上完成的。mod保存我们对Managed object的所有操作,并且允许回退。Managed object对于moc,就像桌上的一个玩具,你可以移动它,毁了它,把它扔出桌面,或是增加新的玩具。桌子就是moc,当你操作完成后,你可以保存moc状态,保存的操作将通过persistent store coordinator

保存persistent store信息,并序列化到磁盘


想在工程中使用core data ,直接在创建的时候勾选use core data(不是所有模板都有的,master-Detail、utility、empty有) ,一旦你勾选use core data,app delegate 将增加以下属性

NSManagedObjectContext *managedObjectContext;

NSManagedObjectModel *managedObjectModel;

NSPersistentStoreCoordinator *persistentStoreCoordinator;



18.1. Creating a Core Data Model with Xcode

可视化设计数据模型

1,找到xcdatamodel文件,点击打开

2,记住Entity相当于数据库中的表,Attribute是表中的列

3,Xcode底部找到加号按钮,长按,在弹出的菜单中选择add Entity,Entities那边将增加一项

4,将新增的项改名Person

5,点击Person,在Attributes面板中通过加号增加下面几项

firstName(string类型)

lastName(string类型)

age(Interger32类型)

6,显示右边栏

7,点击firstName,lastName不勾选optional,点击age勾选optional。

8,保存


18.2. Generating Class Files for Core Data Entities

生产类文件


先完成上一节操作

1,点击xcdatamodel文件

2,选择Person entity

3,File->New File

4,IOS->Core Data->NSManagedObject subclass->next

5,选择你想要保存的managedobjectmodel文件,如:cookbook_7_18_2(以xcdatamodel为后缀的那个文件),然后Next

6,目前我们只创建Person Entity,所以这里只有Person一项,勾选->next

7,保存界面,确保你的target是勾选的,否则,别人可能用不了它,create

OK,导出来了,看下

#import <Foundation/Foundation.h>

#import <CoreData/CoreData.h>



@interface Person : NSManagedObject


@property (nonatomic, retain) NSString * firstName;

@property (nonatomic, retain) NSString * lastName;

@property (nonatomic, retain) NSNumber * age;


@end



@implementation Person


@dynamic firstName;

@dynamic lastName;

@dynamic age;


@end




18.3. Creating and Saving Data Using Core Data

实例化



- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    Person *newPerson = [NSEntityDescription

                         insertNewObjectForEntityForName:@"Person"

                         inManagedObjectContext:self.managedObjectContext];

    

    if (newPerson != nil){

        newPerson.firstName = @"Anthony";

        newPerson.lastName = @"Robbins";

        newPerson.age = @51;

        NSError *savingError = nil;

        if ([self.managedObjectContext save:&savingError]){

            NSLog(@"Successfully saved the context.");

        } else {

            NSLog(@"Failed to save the context. Error = %@", savingError);

        }

    } else {

        NSLog(@"Failed to create the new person.");

    }

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    // Override point for customization after application launch.

    self.window.backgroundColor = [UIColor whiteColor];

    [self.window makeKeyAndVisible];

    return YES;

}


打印:

2014-07-23 10:01:02.485 cookbook7_18_1[386:a0b] Successfully saved the context.

2014-07-23 10:01:02.489 cookbook7_18_1[386:a0b] Application windows are expected to have a root view controller at the end of application launch


NSEntityDescription 的类方法 insertNewObject ForEntityForName:inManagedObjectContext:将从ManagedObjectContext参数中寻找对应第二个参数的entity.如果找到,则返回一个实例,这好比在数据表中插入一条数据。插入数据后要记得提交保存。

如果第二个参数所标记的entity不存在,则会抛出一个NSInternalInconsistencyException异常,比如把@"Person"改成@"Person1",运行

打印:

2014-07-23 10:07:45.250 cookbook7_18_1[408:a0b] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '+entityForName: could not locate an entity named 'Person1' in this model.'


18.4. Reading Data from Core Data

读取数据


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    [self createNewPersonWithFirstName:@"Anthony"

                              lastName:@"Robbins"

                                   age:51];

    [self createNewPersonWithFirstName:@"Richard"

                              lastName:@"Branson"

                                   age:61];

    /* Tell the request that we want to read the

     contents of the Person entity */

    /* Create the fetch request first */

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]

                                    initWithEntityName:@"Person"];

    NSError *requestError = nil;

    /* And execute the fetch request on the context */

    NSArray *persons = [self.managedObjectContext executeFetchRequest:fetchRequest error:&requestError];

    /* Make sure we get the array */

     if ([persons count] > 0){

         /* Go through the persons array one by one */

         NSUInteger counter = 1;

         for (Person *thisPerson in persons){

             NSLog(@"Person %lu First Name = %@", (unsigned long)counter,thisPerson.firstName);

             NSLog(@"Person %lu Last Name = %@", (unsigned long)counter,thisPerson.lastName);

             NSLog(@"Person %lu Age = %ld", (unsigned long)counter,(unsigned long)[thisPerson.age unsignedIntegerValue]); counter++;

         }

     } else {

         NSLog(@"Could not find any Person entities in the context.");

     }


    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    // Override point for customization after application launch.

    self.window.backgroundColor = [UIColor whiteColor];

    [self.window

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值