CoreData

来源:互联网 发布:龙管家网络计费系统 编辑:程序博客网 时间:2024/05/29 15:12

数据库迁移

1.设置coreData的配置为可迁移

数据持久化助理的get方法中:

NSDictionary *option = @{NSMigratePersistentStoresAutomaticallyOption:@(YES)};

options不配置填nil

这里写图片描述

2.添加一个新的集合版本

选中CoreData.xcdatamodeld,editor -> add model version

3.列表内容

在新的版本里给表添加新的字段(2、3的顺序不可以错)

4.选择使用新的版本

右侧的Model Version 的current选新的版本

这里写图片描述

5.桥接两个版本,把老数据库的数据桥接到新数据库

这里写图片描述

这里写图片描述

这里写图片描述

6.生成新的model类

选中CoreData2.xcdatamodeld, editor -> create NSManagedObject subclass… -> next ……

这里写图片描述

若Options选项不选,把int型的字段类型编译为NSNumber

CoreData使用

  1. 临时数据库设为属性

    @property (nonatomic, strong) NSManagedObjectContext *context; // 临时数据库
  2. 在viewDidLoad方法中

    获取appdelegate,把appdelegata的临时数据库赋值给自己的临时数据库

    AppDelegate *delegate = [UIApplication sharedApplication].delegate;_context = delegate.managedObjectContext;
  3. 添加

    假设集合中的表为Person

    Person *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:_context];person.name = @"aa";person.age = 20;person.hobby = @"女";person.sex = @"女";[_context save:nil];
  4. 查找

    // 创建一个用于查找的请求NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];// 创建一个表的描述 (即代表了哪张表)NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:_context];// 设置去哪张表查找[fetchRequest setEntity:entity];// Specify criteria for filtering which objects to fetch// 谓词,可以用作查找的条件。谓词里面的条件是sql语句的查找条件NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@ AND age = 20", @"aa"];// 设置查找的条件[fetchRequest setPredicate:predicate];// Specify how the fetched objects should be sorted// 创建一个排序,具体根据什么排序由key决定,升序或者降序由ascending决定NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];[fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];NSError *error = nil;NSArray *fetchedObjects = [_context executeFetchRequest:fetchRequest error:&error];if (fetchedObjects == nil) {    NSLog(@"请求失败");}for (Person *per in fetchedObjects) {    NSLog(@"nsme:%@ age:%d", per.name, per.age);}
  5. 删除

    [_context deleteObject:Person类对象];[_context save:nil];
0 0