IOS coredata基础。coredata是OC语言对于SQlite的又一次封装,支持自定义对象添加到关系型数据库的表中。sqlite只支持基础数据类型的添加。
下面我们一起通过一个demo来学习一下如何使用coredata
首先新建工程需要勾选上use coredata
然后添加实体,也就是要添加的一张表
按照下图步骤修改实体名,以及添加实体,也就是表中的字段
生成实体,也就是生成表
编译调试,如果报错删除下图对应代码
好了,准备工作完成,接下来我们就可以使用coredata了。还是使用增删改查功能。
首先导入需要的头文件
#import "Person+CoreDataProperties.h"
#import "AppDelegate.h"
case 0:{//增加数据
Person *p = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:app.persistentContainer.viewContext];
p.name = @"李四";
p.age = 32;
Person *p1 = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:app.persistentContainer.viewContext];
p1.name = @"李san";
p1.age = 11;
Person *p2 = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:app.persistentContainer.viewContext];
p2.name = @"旺旺";
p2.age = 21;
[app saveContext];
}
break;
case 1://删除
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
NSArray *persons = [app.persistentContainer.viewContext executeFetchRequest:request error:nil];
for (Person *p in persons) {
// if ([p.name isEqualToString:@"李san"]) {
[app.persistentContainer.viewContext deleteObject:p];
[app saveContext];
// }
}
}
break;
case 2://修改
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
NSArray *persons = [app.persistentContainer.viewContext executeFetchRequest:request error:nil];
for (Person *p in persons) {
if ([p.name isEqualToString:@"李四"]) {
p.name = @"王五";
p.age = 88;
[app saveContext];
}
}
}
break;
case 3://查询
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
NSArray *persons = [app.persistentContainer.viewContext executeFetchRequest:request error:nil];
for (Person *p in persons) {
NSLog(@"%@ %d %@",p.name,p.age,p.objectID);
}
}
break;
}
下面我们来测试一下coredata使用情况
点击添加,再点击查询,结果如下:
然后点击删除,在查询
然后点击修改,在查询
完全符合预期。可以看到coredata可以正常使用