coreData第三方库MagicalRecord

it2022-05-08  7

第一步:添加第三方库,添加框架

第二步:创建数据模型并创建实体

第三步:#import "CoreData+MagicalRecord.h"//该头文件必须添加到.pch的文件中

第四步:

    //初始化数据库信息,名字根据需要写    [MagicalRecord setupCoreDataStackWithStoreNamed:@"model.db"];

主要操作

-(void)buttonClick:(id)sender { UIButton * button = (UIButton *)sender; switch (button.tag) { case 1: { ////<1>创建对象 Student * stu = [Student MR_createEntity]; //<2>对对象的成员属性进行赋值 stu.firstName = @"lele"; stu.lastName = @"du"; stu.age = @"25"; //<3>将对象添加到数据库中 //MR_defaultContext创建上下文对象 //MR_saveOnlySelfAndWait将修改的结果重新写入数据库 [[NSManagedObjectContext MR_defaultContext] MR_saveOnlySelfAndWait]; } break; case 2: { // Student * stu = [Student MR_findFirst]; if (stu) { [stu MR_deleteEntity];//从内存中删除对象 } //从数据库中删除对象 [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait]; } break; case 3: { // NSArray * array = [Student MR_findByAttribute:@"age" withValue:@"30"]; for (Student * str in array) { str.lastName = @"hello"; str.firstName = @"china"; str.age = @"lele"; } [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait]; } break; default: { ////<1>按照条件查询 NSArray * array = [Student MR_findByAttribute:@"age" withValue:@"25"]; for (Student * str in array) { NSLog(@"%@",str.lastName); } //<2>查询数据库中所有数据信息 NSArray * array1 = [Student MR_findAll]; for (Student * str in array1) { NSLog(@"%@",str.lastName); } //<3>查询数据库中第一个数据信息 Student * stu = [Student MR_findFirst]; NSLog(@"%@",stu.firstName); } break; } }

 

 

转载于:https://www.cnblogs.com/huoxingdeguoguo/p/4625261.html


最新回复(0)