CoreData
// 获取AppDelegate的context属性
NSManagedObjectContext *context = ((AppDelegate *)[UIApplication sharedApplication].delegate).managedObjectContext;
// 创建实体描述,并且关联上下文
NSEntityDescription *guoguoEntity = [NSEntityDescription entityForName:@"Guoguo" inManagedObjectContext:context];
- 1 增
// 根据描述创建对象,并插入到context
GoldOne *person = [[GoldOne alloc] initWithEntity:goldOneEntity insertIntoManagedObjectContext:context];
person.name = [NSString stringWithFormat:@"jinyi%d", i];
person.age = [NSNumber numberWithInt:i];
person.sex = [NSString stringWithFormat:@"男%d", i];
NSError *error;
[context save:&error];
if (error) {
UIAlertView *alertView= [[UIAlertView alloc] initWithTitle:@"提示"message:@"添加失败" delegate:self cancelButtonTitle:nil otherButtonTitles:@"好", nil];
[alertView show];
}
else {
NSLog(@"成功添加");
}
- 2 删
GoldOne *person = ((GoldOne *)self.allDataArray[indexPath.row]);
[self.context deleteObject:person];
[self.allDataArray removeObject:person];
[self.context save:nil];
[tableView reloadData];
- 3 改
// 改第一个数组的值
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"GoldOne"];
NSArray *array = [self.context executeFetchRequest:request error:nil];
GoldOne *person = array[0];
person.name = dict[@"name"];
person.age = dict[@"age"];
person.sex = dict[@"sex"];
[self.tableView reloadData];
- 4 查
// 创建一个请求对象
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"GoldOne"];
// 利用KVC编码,避免bug
[request setReturnsObjectsAsFaults:NO];
// 创建一个数组请求里面的排序对象
// NSSortDescriptor *sortD = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:YES];
// request.sortDescriptors = @[sortD];
// 直接匹配
// request.predicate = [NSPredicate predicateWithFormat:@"name = %@", @"dada"];
// 含有通配符的
request.predicate = [NSPredicate predicateWithFormat:@"name like %@", @"dada"];
// 以什么开头
request.predicate = [NSPredicate predicateWithFormat:@"name beginswith %@", @"dada"];
// 以什么结尾
request.predicate = [NSPredicate predicateWithFormat:@"name like %@", @"dada"];
// 包含什么
request.predicate = [NSPredicate predicateWithFormat:@"name contains %@", @"11"];
NSError *error;
NSArray *array = [self.context executeFetchRequest:request error:&error];
if (error) {
return;
}
NSLog(@"%@", _array);
[self.tableView reloadData];
- 5 CoreData的model更新
添加后更改Model Version的Current
然后再重新创建Entity的model
再到AppDelegate里的如下方法中添加如下代码
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
...
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
return _persistentStoreCoordinator;
}
最后在上述方法中找到如下代码,把options后的nil改为options即可
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
...
}