Xcode8后coreData的使用简介

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

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

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


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.运行程序,可以对其进行调试。

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容