CoreData浅谈

来源:互联网 发布:淘宝手机助手集分宝 编辑:程序博客网 时间:2024/06/08 07:41

什么是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:requesterror:&error];

    //给数据源数组中添加数据

    [self.dataSourceaddObjectsFromArray:result];

}




0 0
原创粉丝点击