iOS中Core Data的使用

使用MagicalRecord操作CoreData数据库


一、iOS中Core Data的创建与表的创建以及数据表数据模型类的创建

iOS工程中创建CoreData数据库的方法:

方法一:在创建工程时勾选Use Core Data选项自动创建CoreData数据库

方法二:在工程中右键New File选择iOS中的Core Data选择再选择Data Model创建Core Data


在CoreData中新增数据表:

点击创建好的Core Data数据库点击Add Entity创建一张新的数据库表,在数据库表中填入字段


生成数据库表对应的模型类:

点击创建好的Core Data数据库,然后Editor-->Create  NSManagedObject Subclass...-->选择要创建数据模型类的数据库点击next-->选择要创建数据模型类的数据表点击Next--->选择存储位置


二、iOS中通过MagicalRecord第三方库操作Core Data

第一步:

使用cocoapods导入MagicalRecord第三方库;

第二步:

在需要对Core Data操作的类中导入MagicalRecord,例如:#import  <MagicalRecord/MagicalRecord.h>


第三步:MagicalRecord对Core Data的操作

/// @brief 以下用UserInfoRecord代表数据表模型类


@brief 设置数据库存放的文件名

[MagicalRecord  setupCoreDataStackWithStoreNamed:@"Model.sqlite"];


/// @brief 让MagicalRecord支持数据库版本管理

[MagicalRecord  setupAutoMigratingCoreDataStack];


/// @brief 使用MagicalRecord操作Core Data往数据表中增加一条数据

/// @brief 增加一条记录

    UserInfoRecord *newUserInfoRecord = [UserInfoRecord MR_createEntity];

    newUserInfoRecord.identity = @"1";

    newUserInfoRecord.name = @"张凡";

    newUserInfoRecord.image = [NSUUID UUID].UUIDString;

    newUserInfoRecord.age = @21;

    /// @brief 保存

    [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];



/// @brief 删除数据

在删之前需要先查

查询符合条件的数据

NSArray  *deleteUsers = [UserInfoRecord  MR_findByAttribute:@"age" withValue:@"21"];

forin(UserInfoRecord  *user  in  deleteUsers){

/// @brief 删除数据

[user  MR_deleteEntity];

}

/// @brief 保存

[[NSManagedObjectContext  MR_defaultContext]  MR_saveToPersistentStoreAndWait];



///  @brief 修改数据

修改之前需要先查询到数据

///  @brief  查询到符合条件的数据

NSArray  *updateUsers = [UserInfoRecord  MR_findByAttribute:@"age"  withValue:@"21"];

for(UserInfoRecord  *user  in  updateUsers){

/// @brief 修改数据

user.age = @30;

}

///  @brief  保存数据

[[NSManagedObjectContext  MR_defaultContext]  MR_saveToPersistentStoreAndWait];


///  @brief 数据查询

/// @brief 查询表中的所有数据

NSArray  *allUsers = [UserInfoRecord  MR_findAll];

///  @brief 查询表中符合条件的数据

NSArray  *users = [UserInfoRecord  MR_findByAttribute:@"age"];

///  @brief  多条件查询

NSPredicate  *predicate = [NSPredicate  predicateWithFormat:@"name=%@ and age=%@",@"张三",@"23"];

NSArray *users = [UserInfoRecord  MR_findAllWithPredicate:predicate];

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值