1.首先新建一个工程,在建立工程时记得勾选use coredata
2.系统会自动创建coredata,点击它,如图:
3.对coredata进行增删改查操作
(1)导入school和student的头文件 School+CoreDataProperties.h,Student+CoreDataClass.h
@property (nonatomic , strong) AppDelegate *appdelegate;
self.appdelegate =(AppDelegate *)[UIApplicationsharedApplication].delegate;
(2) 添加数据
NSEntityDescription *entityDescription = [NSEntityDescriptionentityForName:@"School"inManagedObjectContext:self.appdelegate.
persistentContainer.viewContext];
School *school = [[Schoolalloc]initWithEntity:entityDescriptioninsertIntoManagedObjectContext:self.appdelegate.persistentContainer.
viewContext];
school.name = @“清华大学”;
school.area = @“北京”;
[self.appdelegatesaveContext];
for (int i = 0; i < 3 ; i ++) {
Student *student = [NSEntityDescriptioninsertNewObjectForEntityForName:@"Student"inManagedObjectContext:self.appdelegate.persistentContainer.viewContext];
student.name =[NSString stringWithFormat:@"学生%d",i];
student.number =[NSString stringWithFormat:@"00%d",i+10];
student.stu_school = school;
[self.appdelegatesaveContext];
}(3) 查询数据
NSFetchRequest *fetchRequest = [[NSFetchRequestalloc] init];
NSEntityDescription *entity = [NSEntityDescriptionentityForName:@"School"inManagedObjectContext:self.appdelegate.persistentContainer.viewContext];
[fetchRequest setEntity:entity];
NSError *error =nil;
self.schoolArr = [[self.appdelegate.persistentContainer.viewContextexecuteFetchRequest:fetchRequest error:&error] mutableCopy];
if (self.schoolArr ==nil) {
NSLog(@"------");
}else {
for (School *schoolin self.schoolArr) {
for (Student *studentin school.school_stu) {
NSLog(@"==%@",student.name);
}
NSLog(@"%@---%@",school.name,school.area);
}
}
(4) 修改数据
School *school =self.schoolArr[0];
school.name = @"深圳大学";
school.area = @"深圳";
[self.appdelegatesaveContext];
(5) 删除数据
School *school = self.schoolArr[0];
[self.appdelegate.persistentContainer.viewContextdeleteObject:school];
[self.appdelegatesaveContext];