Xcode8后coreData的使用简介

该文章本来是以前在CSDN上写的,后面由于编辑方式不如,就将其copy到了。
下面就简单的介绍一下怎么使用coreData

1.首先新建一个工程,在建立工程时记得勾选use coredata

2.系统会自动创建coredata,点击它,如图:


Xcode8后coreData的使用简介_第1张图片
20170331154446172.png

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:fetchRequesterror:&error] mutableCopy];
    if (self.schoolArr == nil) {
        NSLog(@"------");
    }else {
        for (School *schoolinself.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.appdelegate saveContext];

(5) 删除数据

 School *school = self.schoolArr[0];
 [self.appdelegate.persistentContainer.viewContextdeleteObject:school];
 [self.appdelegate saveContext];

4.运行程序,可以对其进行调试。

注意:如果模型发生了变化,此时可以重新生成实体类文件,所生成的数据库并会自动更新,不需要做额外的操作。

你可能感兴趣的:(Xcode8后coreData的使用简介)