CoreData编程

另一个常用数据库:realm

创建支持CoreData的应用


第一步.png

CoreData支持可视化的创建数据模型


第二步.png

每一个实体(Entity)对应一个model类
第三步.png

给实体添加属性,对应数据库中的字段


第四步.png
保存数据
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    //获取管理上下文, 可以理解为"数据库"
    //Xcode版本以前用: NSManagedObjectContext *context =appDelegate.managedObjectContext;
    NSManagedObjectContext *context = appDelegate.persistentContainer.viewContext;
    //使用实体名称创建一个实体(描述对象)
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:context];
    //使用实体描述创建管理对象,并且插入管理上下午("数据库"),并没有持久化
    NSManagedObject *student = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:context];
    [student setValue:@"张三" forKey:@"name"];
    [student setValue:@22 forKey:@"age"];
    [student setValue:@"长沙" forKey:@"address"];
    //持久化(保存)
    if ([context save:nil]) {
        NSLog(@"save success");
    }
获取数据
AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    NSManagedObjectContext *context = appDelegate.persistentContainer.viewContext;
    //使用实体名创建数据请求对象
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Student"];
    //执行数据请求
    NSArray *arr = [context executeFetchRequest:request error:nil];
    NSLog(@"----->%@", arr);

创建NSManagedObject子类

1.png

2.png
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    NSManagedObjectContext *context = appDelegate.persistentContainer.viewContext;
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:context];
    Student *student = [[Student alloc] initWithEntity:entity insertIntoManagedObjectContext:context];
    //存
    student.name = @"张三";
    student.age = 31;
    student.address = @"长沙";
    if ([context save:nil]) {
        NSLog(@"保存成功");
    }
    //取
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Student"];
    NSArray *arr = [context executeFetchRequest:request error:nil];
    for (Student *stu in arr) {
        NSLog(@"------->%@: %hd", stu.name, stu.age);
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容