1.创建程序时勾选coredata
2.在core.xcdatamodeld文件中建立表User
使用时,先为User表创建modal类,继承自NSManagedObject
在AppDelegate中会有自动生成的几个属性用来数据库访问等
数据库增删改查过程:先将结果查询出来,在查询出来的结果上进行数据操作,最后再保存回去
1.增
User *user = [NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:self.managedObjectContext]; // 返回插入的数据项 user.name = @"gaoxinchuan"; // 设置属性内容 user.age = [NSNumber numberWithInt:6]; NSError *error = nil; BOOL isSave = [self.managedObjectContext save:&error]; // 保存即可 if (!isSave) { NSLog(@"error:%@,%@",error,[error userInfo]); } else{ NSLog(@"保存成功"); }
2.删
// 实现原理 // 将结果查询出来,在查询出来的结果上操作,最后再保存回去 NSEntityDescription *description = [NSEntityDescription entityForName:@"User" inManagedObjectContext:self.managedObjectContext]; // 设置查询集合 NSFetchRequest *request = [[NSFetchRequest alloc] init]; [request setIncludesPropertyValues:NO]; [request setEntity:description]; NSError *error = nil; NSArray *datas = [self.managedObjectContext executeFetchRequest:request error:&error]; // 进行查询 if (!error && datas && [datas count]) { for (NSManagedObject *obj in datas) { [self.managedObjectContext deleteObject:obj]; // 删除数据项 } if (![self.managedObjectContext save:&error]) // 保存最后结果,同步到数据库 { NSLog(@"error:%@",error); } }
3.改
NSEntityDescription *description = [NSEntityDescription entityForName:@"User" inManagedObjectContext:self.managedObjectContext]; NSFetchRequest *request = [[NSFetchRequest alloc] init]; [request setIncludesPropertyValues:NO]; [request setEntity:description]; NSError *error = nil; NSArray *datas = [self.managedObjectContext executeFetchRequest:request error:&error]; if (!error && datas && [datas count]) { for (User *obj in datas) { obj.name = @"haizeiwang"; // 修改数据 } if (![self.managedObjectContext save:&error]) // 同步到数据库 { NSLog(@"error:%@",error); } }
4.查
//创建取回数据请求 NSFetchRequest *request = [[NSFetchRequest alloc] init]; request.predicate = [NSPredicate predicateWithFormat:@"name == @‘gaoxinchuan‘"]; //设置要检索哪种类型的实体对象 NSEntityDescription *entity = [NSEntityDescription entityForName:@"User"inManagedObjectContext:self.managedObjectContext]; //设置请求实体 [request setEntity:entity]; //指定对结果的排序方式 NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name"ascending:NO]; NSArray *sortDescriptions = [[NSArray alloc]initWithObjects:sortDescriptor, nil]; [request setSortDescriptors:sortDescriptions]; NSError *error = nil; //执行获取数据请求,返回数组 NSMutableArray *mutableFetchResult = [[self.managedObjectContext executeFetchRequest:request error:&error] mutableCopy]; if (mutableFetchResult == nil) { NSLog(@"Error: %@,%@",error,[error userInfo]); } self.dataArray = mutableFetchResult; for (User *dog in self.dataArray) { NSLog(@"age:%@--name:%@",dog.age,dog.name); }
5.可以设置查询条件:NSPredicate
时间: 2024-10-03 09:42:32