您的位置:首页 > 其它

CoreData浅谈

2016-06-03 11:09 267 查看
什么是coredata?

第一、CoreData并不属于数据库,而是苹果公司封装的进行数据持久化的框架;

第二、CareData不仅支持SQLite文件,而且支持XML、二进制文件.

(一)插入数据

- (IBAction)addModel:(id)sender {
    //创建实体描述对象
    NSEntityDescription *description = [NSEntityDescriptionentityForName:@"Cloese"inManagedObjectContext:self.mydelegate.managedObjectContext];
    //1.先创建模型对象
    Cloese *cloese = [[Cloesealloc]
initWithEntity:descriptioninsertIntoManagedObjectContext:self.mydelegate.managedObjectContext];
    cloese.name =@"Lucy";
    int price =arc4random() %
100 +1;
    cloese.price = [NSNumbernumberWithInt:price];
    //插入数据源数组
    [self.dataSourceaddObject:cloese];
    [self.tableviewinsertRowsAtIndexPaths:@[[NSIndexPathindexPathForRow:self.dataSource.count
-1 inSection:0]]withRowAnimation:UITableViewRowAnimationLeft];
    //对数据管理器中的更改进行存储
    [self.mydelegatesaveContext];
}

(二)删除数据

//允许tableview可编辑
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    returnYES;
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle ==UITableViewCellEditingStyleDelete) {
        //删除数据源
        Cloese *cloese =self.dataSource[indexPath.row];
        [self.dataSourceremoveObject:cloese]; 
        //删除数据管理器的数据
        [self.mydelegate.managedObjectContextdeleteObject:cloese];
        //将进行的更改进行保存
        [self.mydelegatesaveContext]; 
        //删除单元格
        [self.tableviewdeleteRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationFade];
    }
}
(三)修改数据

//点击cell的方法用来修改数据
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //先找到模型对象
    Cloese *cloese =self.dataSource[indexPath.row];
    cloese.name =@"小福子";
    cloese.price = [NSNumbernumberWithInt:213];
    [self.tableviewreloadRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationAutomatic];
    //将进行的更改进行保存
    [self.mydelegatesaveContext];
}
(四)查询数据

- (void)viewDidLoad {
    [superviewDidLoad];
    self.dataSource = [NSMutableArrayarray];
    self.mydelegate = [UIApplicationsharedApplication].delegate;
    //查询数据
    NSFetchRequest *request = [[NSFetchRequestalloc]
initWithEntityName:@"Cloese"];
    NSSortDescriptor *sort = [[NSSortDescriptoralloc]
initWithKey:@"price"ascending:YES];
    request.sortDescriptors =@[sort];
    //执行查询
    NSError *error =nil;
    NSArray *result = [self.mydelegate.managedObjectContextexecuteFetchRequest:request
error:&error];
    //给数据源数组中添加数据
    [self.dataSourceaddObjectsFromArray:result];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  coredata