CoreData主要提供对象-关系映射功能,把OC对象转换成数据存储到文件中,也可以将数据转换成OC对象;主要优势:可以实现可视化,支持苹果官方API;
步骤图:
然后开始代码:
//第一步:在controller中引入头文件appdelegate
#import "AppDelegate.h"
//第二步:在延展中什么管理对象上下文对象
@property (nonatomic, strong) NSManagedObjectContext *managedObjectContext;
//第三步:懒加载
- (NSManagedObjectContext *)managedObjectContext {
//因为在APPDelegate中已经实现过了,所以在这里是从APPDelegate中获取
if (_managedObjectContext == nil) {
//获取APPDelegate对象
AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
_managedObjectContext = appDelegate.managedObjectContext;
}
return _managedObjectContext;
}
//添加对象
#pragma mark - 添加人
- (void)addPerson {
//1.添加步骤创建person实体对象,
Person *per = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.managedObjectContext];
//2.给对象属性赋值
per.personName = @"llly";
per.personGender = @"Unknow";
per.personAge = @12;
//3.将person对象存入数据库
BOOL result = [_managedObjectContext save:nil];
//4.判断是否添加成功
if (result) {
NSLog(@"添加数据成功");
} else {
NSLog(@"添加数据失败");
}
}
#pragma mark - 删除人
- (void)deletePerson {
//1.实体化请求类【查询】
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
//2.找到删除的条件(根据什么进行删除)[NSPredicate谓词]
request.predicate = [NSPredicate predicateWithFormat:@"personName = 'llly'"];//双引号里面不能继续使用双引号所以讲llly改为单引号
//3.由context根据删除条件的请求去进行删除操作
NSArray *resultArray = [self.managedObjectContext executeFetchRequest:request error:nil];
//4.遍历搜索出来的结果
for (Person *per in resultArray) {
//删除查询到的相关人的信息
[self.managedObjectContext deleteObject:per];
}
//5.进行删除结果的判断
BOOL result = [_managedObjectContext save:nil];
//6.判断
if (result) {
NSLog(@"删除成功");
} else {
NSLog(@"删除失败");
}
}
#pragma mark - 更新人的信息-步骤类似
- (void)updatePerson {
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"personName = 'llly'"];
NSArray *resultArray = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];
for (Person *per in resultArray) {
per.personName = @"小强";
//将名字为llly的对象的姓名改成小强
//NSLog(@"name = %@, gender = %@, age = %@", per.personName, per.personGender, per.personAge);
}
//5.进行更新结果的判断
BOOL result = [_managedObjectContext save:nil];
if (result) {
NSLog(@"更新成功");
} else {
NSLog(@"更新失败");
}
}
#pragma mark - 查询相关信息-步骤类似
- (void)selectAllPerson {
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"personName LIKE '*强'"];
fetchRequest.predicate = predicate;
NSArray *resultArray = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];
for (Person *per in resultArray) {
NSLog(@"======name = %@, gender = %@, age = %@", per.personName, per.personGender, per.personAge);
}
}