美文网首页
CoreData编程

CoreData编程

作者: Dove_Q | 来源:发表于2016-10-20 16:50 被阅读30次

另一个常用数据库: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);
    }

相关文章

网友评论

      本文标题:CoreData编程

      本文链接:https://www.haomeiwen.com/subject/hwefuttx.html