coreData的增删改查

#import "ViewController.h"

#import "Student.h"

 

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>

{

    NSManagedObjectContext * _context; //上下文

    NSIndexPath * _selectIndexPath; //记录选中的cell

}

 

@property (nonatomic,strong) NSMutableArray * dataSource;

@property (weak, nonatomic) IBOutlet UITextField *name;

@property (weak, nonatomic) IBOutlet UITextField *age;

@property (weak, nonatomic) IBOutlet UITableView *tableView;

 

@end

 

@implementation ViewController

 

-(NSMutableArray*)dataSource

{

    if (_dataSource == nil) {

        _dataSource = [NSMutableArray array];

    }

    return _dataSource;

}

 

- (void)viewDidLoad {

    [super viewDidLoad];

  

    //1、准备coreData,获取贯通上层实体和底层数据库的上下文

    [self prepareCoreData];

    

    //2、加载所有的数据

    [self loadData];

}

 

-(void)loadData

{

    //查询保存的所有数据

    NSFetchRequest * request = [[NSFetchRequest alloc]init];

    //设置你要查询的实体

    request.entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:_context];

    //具体的查询条件(不设)

    

    //执行查询

    NSArray * array = [_context executeFetchRequest:request error:nil];

    //先清空数据源

    [self.dataSource removeAllObjects];

    [self.dataSource addObjectsFromArray:array];

    [self.tableView reloadData];

}

 

-(void)prepareCoreData

{

    //1、获取momd文件的路径

    NSString * path = [[NSBundle mainBundle]pathForResource:@"Model" ofType:@"momd"];

    //2、从momd文件中取出所有的实体

    NSManagedObjectModel * models = [[NSManagedObjectModel alloc]initWithContentsOfURL:[NSURL fileURLWithPath:path]];

    //3、创建持久化的数据协调器,创建本身就已经关联了上层实体

    NSPersistentStoreCoordinator * coordinator = [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:models];

    

    //4、让协调器关联数据库

    //指明数据库的路径

    NSString * dbPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/StudentDB"];

    //关联

    NSError * error;

    [coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:dbPath] options:nil error:&error];

    if (error == nil) {

        NSLog(@"关联成功");

    }

 

    //5、创建上下文

    _context = [[NSManagedObjectContext alloc]initWithConcurrencyType:NSMainQueueConcurrencyType];

    _context.persistentStoreCoordinator = coordinator;

 

}

 

//添加

- (IBAction)add:(id)sender {

    //学生的空实体

    Student * stu = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:_context];

    //对个属性赋值

    stu.name = self.name.text;

    stu.age = [NSNumber numberWithInteger:[self.age.text integerValue]];

    

    //使用上下文,保存操作。

    BOOL success =  [_context save:nil];

    if (success == YES) {

        NSLog(@"添加新对象成功");

        //刷新数据

        [self loadData];

    }

}

 

- (IBAction)delete:(id)sender {

    //拿到你要删除的对象

    Student * stu = self.dataSource[_selectIndexPath.row];

    //2、删除

    [_context deleteObject:stu];

    

    //3、保存执行的操作

    BOOL success =  [_context save:nil];

    if (success == YES) {

        //刷新列表

        [self loadData];

    }

}

 

- (IBAction)update:(id)sender {

    //插叙要修改的对象

    NSFetchRequest * request = [[NSFetchRequest alloc]init];

    //设置查询实体

    request.entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:_context];

    //设置查询谓语

   request.predicate = [NSPredicate predicateWithFormat:@"age<20"];

    

    //执行查询

    NSArray * array = [_context executeFetchRequest:request error:nil];

    

    for (Student * stu in array) {

        stu.name = @"汉武大帝";

        stu.age = [NSNumber numberWithInteger:24];

    }

    

    //保存修改的结果

    BOOL success = [_context save:nil];

    if (success == YES) {

        NSLog(@"数据修改成功");

        [self loadData];

    }

}

 

- (IBAction)select:(id)sender {

    //查询要修改的对象

    NSFetchRequest * request = [[NSFetchRequest alloc]init];

    //设置查询实体

    request.entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:_context];

    //设置查询谓语

    request.predicate = [NSPredicate predicateWithFormat:@"age<24"];

    

    //执行查询

    NSArray * array = [_context executeFetchRequest:request error:nil];

    

    //显示

    [self.dataSource removeAllObjects];

    [self.dataSource addObjectsFromArray:array];

    [self.tableView reloadData];

    

}

 

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    return self.dataSource.count;

}

 

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];

    if (cell == nil) {

        cell = [[ UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];

    }

    Student * stu = self.dataSource[indexPath.row];

    cell.textLabel.text = stu.name;

    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@",stu.age];

    

    return cell;

}

 

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

    _selectIndexPath = indexPath;

}

 

 

 

 

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

 

@end

 

转载于:https://my.oschina.net/u/3389486/blog/868504

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值