CoreData编程
2016-10-20 本文已影响30人
Dove_Q
另一个常用数据库:realm
创建支持CoreData的应用

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

每一个实体(Entity)对应一个model类

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

保存数据
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子类


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);
}