iOS CoreData的基本用法

基本介绍:
CoreData是iOS5之后新出来的的一个框架, 是对SQLite进行一层封装升级后的一种数据持久化方式. 它提供了对象—关系映射的功能, 即能够将OC对象转化
为数据存储到SQLite数据库文件中, 同时也能将数据库中的数据还原成OC对象. 相较于SQLite, 我们使用CoreData就不需要再编写任何SQL语句.

核心对象:
1. NSManagedObjectContext  管理对象上下文, 作用: 负责应用和数据之间的交互, 用来对数据进行查询 增加 更新 删除
2. NSManagedObjectModel 管理对象模型  代表CoreData的模型文件, 相当于实体, 包含了实体之间的相互关系
3. NSPersistentStoreCoordinator 持久化存储助理  相当于数据库的连接器
4. NSEntityDescription 实体描述  用来描述实体

模型对象:

1. 选择模板:

2. 添加实体 命名为Person

3. 给Person实体添加name属性并设置属性的数据类型, 注意: 属性的首字母不能大写

4.同样的方式创建一个Card实体并添加no属性 数据类型设置为Interger16 注:实际上的类型为NSNumber *类型

5.建立Person和Card之间的关联关系 
第1和第2 表示Person实体中有一个Card类型的card属性

同样在Card实体中进行操作, 其中第3选项 选择card 表示Person中有一个card属性 同时到Card中点击3选项选上person 这样就建立起了Person和Card中的一对一关联关系

创建NSManagedObject的子类

默认情况下, 利用CoreData取出的实体都是NSManagedObject类型的, 能够利用键值对来存取数据. 但是一般情况下, 实体在存取数据的基础上, 有时还需要添加一些业务方法来处理其他任务, 那就必须创建NSManagedObject的子类.

接下来用Storyboars创建一个UITableVIewController并且建一个类与其关联一下, 具体过程就不在累赘.

增加CoreData.framework在需要使用CordData的地方导入三个头文件
#import <CoreData/CoreData.h>
#import "Person.h"
#import "Card.h"


//搭建上下文环境
- (void)configureContext
{
    /**
     *  1. 初始化NSManagedObjectModel对象, 加载模型文件, 读取app中的所有实体信息
        2. 初始化NSPersistentStoreCoordinator对象, 添加持久化数据库(这里使用SQLite数据库)
        3. 初始化NSManagerObjectContext对象, 拿到这个上下文对象操作实体, 进行CRUD(查询增加更改删除)操作
     */
    //从应用程序包中加载模型文件
    NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
    //传入模型文件, 初始化 持久化数据库协调器
    NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:model];
    //构建SQLite数据库文件路径
    NSString *docs = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSURL *url = [NSURL fileURLWithPath:[docs stringByAppendingPathComponent:@"person.data"]];
    //添加持久化数据库 这里使用SQLite作为持久库
    NSError *error = nil;
    NSPersistentStore *store = [psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:&error];
    if (nil == store) {
        //直接抛弃异常
        [NSException raise:@"添加数据库错误" format:@"%@", [error localizedDescription]];
    }
    //初始化上下文 配置持久化库协调器属性
    self.context = [[NSManagedObjectContext alloc] init];
    _context.persistentStoreCoordinator = psc;
}

//增加
- (IBAction)addAction:(UIBarButtonItem *)sender {
    //根据管理对象上下文对象 创建一个Person实体对象
    Person *per = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:_context];    //配置属性
    NSArray *nameArr = @[@"小一", @"小二", @"小三", @"小四"];
    per.name = nameArr[arc4random() % 4];
    Card *card = [NSEntityDescription insertNewObjectForEntityForName:@"Card" inManagedObjectContext:_context];
    card.no = [NSNumber numberWithInt:arc4random() % 100 + 100];
    per.card = card;
    //存储
    [self saveContextSuccessHandler:^{
        //存储本地成功
        //内存中添加一份
        [self.arr addObject:per];
        //刷新tableView的一条数据
        [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.arr.count - 1 inSection:0]] withRowAnimation:UITableViewRowAnimationLeft];
        //tableView滚动到最下方
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.arr.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    } failedHandler:^(NSError *error) {
        //保存到本地失败
    }];
}

//存储
- (void)saveContextSuccessHandler:(void(^)())successHandler failedHandler:(void(^)(NSError *error))failedHandler
{
    NSError *error = nil;
    [_context save:&error];
    if (nil != error) {
        if (nil != failedHandler) {
            failedHandler(error);
        }
    } else {
        if (nil != successHandler) {
            successHandler();
        }
    }
}

//删除操作
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        //获取要删除的对象
        Person *per = self.arr[indexPath.row];
        //从数据库中删除
        [_context deleteObject:per];
        //保存一下
        [_context save:NULL];
        //从内存中删除
        [self.arr removeObject:per];
        //在tableView上删除
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
//    [[NSFileManager defaultManager] removeItemAtURL:[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] error:nil];
    [self configureContext];
    //读取数据
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
    //设置查询条件
//    fetchRequest.predicate = [NSPredicate predicateWithFormat:@"name == '小三'"];
    NSArray *perArr = [_context executeFetchRequest:fetchRequest error:NULL];
    self.arr = [NSMutableArray arrayWithArray:perArr];
}


可在这里下载工程(包含了版本迁移的工程):http://download.csdn.net/detail/kiushuo/7842641

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值