#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