CoreData

  1 #import "ClassController.h"
  2 #import "LOClass.h"
  3 #import "Student.h"
  4 #import "Teacher.h"
  5 #import "AppDelegate.h"
  6 #import "StudentController.h"
  7 @interface ClassController ()
  8 @property (nonatomic,strong) NSMutableArray *classArray;
  9 @property (nonatomic,strong)NSManagedObjectContext *mContext;
 10 @end
 11 
 12 @implementation ClassController
 13 -(NSMutableArray *)classArray
 14 {
 15     if (_classArray == nil) {
 16         _classArray = [NSMutableArray new];
 17     }
 18     return _classArray;
 19 }
 20 - (void)viewDidLoad {
 21     [super viewDidLoad];
 22     AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
 23     //获取数据管理器类
 24     self.mContext = appDelegate.managedObjectContext;
 25    
 26 }
 27 -(void)viewWillAppear:(BOOL)animated
 28 {
 29     [super viewWillAppear:animated];
 30     [self reloadClass];
 31 }
 32 static NSString *reuseIdentifier = @"cell";
 33 //获取所有班级的方法
 34 -(NSArray *)getAllClass
 35 {
 36     //创建查询请求
 37     NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"LOClass"];
 38     //实体属性
 39     NSEntityDescription *LOClassED = [NSEntityDescription entityForName:@"LOClass" inManagedObjectContext:self.mContext];
 40     fetchRequest.entity = LOClassED;
 41     //排序属性
 42     NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
 43     fetchRequest.sortDescriptors = @[sort];
 44     //谓词,不写表示查询所有的
 45     //返回查询结果
 46     return [self.mContext executeFetchRequest:fetchRequest error:nil];
 47 }
 48 
 49 - (IBAction)addClassAction:(UIBarButtonItem *)sender {
 50     //实体描述
 51     NSEntityDescription *classED = [NSEntityDescription entityForName:@"LOClass" inManagedObjectContext:self.mContext];
 52     //创建班级
 53     LOClass *loClass = [[LOClass alloc] initWithEntity:classED insertIntoManagedObjectContext:self.mContext];
 54     //给属性赋值
 55     
 56     loClass.name = [NSString stringWithFormat:@"研%d",arc4random()%20 + 1];
 57     loClass.address = @"金五星商厦蓝鸥科技";
 58     NSSet *studentSet = [NSSet setWithArray:[self studentArray]];
 59     //建立表关系
 60     [loClass addStudentRelation:studentSet];
 61     
 62     //创建老师的实体描述
 63     NSEntityDescription *teacherED = [NSEntityDescription entityForName:@"Teacher" inManagedObjectContext:self.mContext];
 64     Teacher *tea = [[Teacher alloc] initWithEntity:teacherED insertIntoManagedObjectContext:self.mContext];
 65     tea.name = [NSString stringWithFormat:@"王%d",arc4random()%30];
 66     tea.course = @"编程";
 67     //建立与老师的表关系
 68     loClass.techerRelation = tea;
 69     
 70     //保存
 71     NSError *error = nil;
 72     [self.mContext save:&error];
 73     if (error) {
 74         NSLog(@"保存失败,错误:%@",error);
 75     }
 76     //刷新 班级
 77     [self reloadClass];
 78 }
 79 //刷新tableView的班级
 80 -(void)reloadClass
 81 {
 82     [self.classArray removeAllObjects];
 83     [self.classArray addObjectsFromArray:[self getAllClass]];
 84     [self.tableView reloadData];
 85 }
 86 
 87 //随机创建学生
 88 -(NSArray *)studentArray
 89 {
 90     NSInteger count = arc4random()%20 + 11;
 91     NSMutableArray *arr = [NSMutableArray array];
 92     for (int i = 0; i < count; i++) {
 93         NSEntityDescription *studentED = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:self.mContext];
 94         Student *stu = [[Student alloc] initWithEntity:studentED insertIntoManagedObjectContext:self.mContext];
 95         stu.name = [NSString stringWithFormat:@"张%d",arc4random()%50];
 96         stu.age = @(arc4random()%30 + 18);
 97         stu.gender = arc4random()%2?@"":@"";
 98         //添加到数组里
 99         [arr addObject:stu];
100         
101     }
102     return arr;
103 }
104 
105 - (void)didReceiveMemoryWarning {
106     [super didReceiveMemoryWarning];
107     // Dispose of any resources that can be recreated.
108 }
109 
110 #pragma mark - Table view data source
111 
112 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
113 
114     return 1;
115 }
116 
117 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
118 
119     return self.classArray.count;
120 }
121 
122 
123 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
124     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier forIndexPath:indexPath];
125     LOClass *loClass = self.classArray[indexPath.row];
126     cell.textLabel.text = loClass.name;
127     
128     
129     return cell;
130 }
131 //进行传值
132 -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
133 {
134     StudentController *studentVC = [segue destinationViewController];
135     NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
136     studentVC.loClass = self.classArray[indexPath.row];
137 }
138 // Override to support conditional editing of the table view.
139 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
140     // Return NO if you do not want the specified item to be editable.
141     return YES;
142 }
143 
144 
145 
146 // Override to support editing the table view.
147 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
148     if (editingStyle == UITableViewCellEditingStyleDelete) {
149         //1.先从数据库里进行删除
150         
151         //创建查询请求
152         NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"LOClass"];
153         //创建实体描述
154         NSEntityDescription *classED = [NSEntityDescription entityForName:@"LOClass" inManagedObjectContext:self.mContext];
155         //设置查询条件的实体属性
156         fetchRequest.entity = classED;
157         //创建查询条件
158         LOClass *loClass = self.classArray[indexPath.row];
159         NSString *name = loClass.name;
160         NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name = %@",name];
161         //设置查询请求的谓词属性
162         fetchRequest.predicate = predicate;
163         //创建排序器 NSSortDescription
164         NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
165         fetchRequest.sortDescriptors = @[sort];
166         NSArray *result = [self.mContext executeFetchRequest:fetchRequest error:nil];
167         for (LOClass *loClass in result) {
168             [self.mContext deleteObject:loClass];
169         }
170         [self.mContext save:nil];
171         
172         //2.从内存中删除
173         [self.classArray removeObjectAtIndex:indexPath.row];
174         
175         //3.从视图上删除
176         [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
177     } else if (editingStyle == UITableViewCellEditingStyleInsert) {
178         // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
179     }
180 }
181 
182 @end
1 #import <UIKit/UIKit.h>
2 #import "LOClass.h"
3 @interface StudentController : UITableViewController
4 @property (nonatomic,strong) LOClass *loClass;
5 @end
 1 #import "StudentController.h"
 2 #import "student.h"
 3 #import "AppDelegate.h"
 4 @interface StudentController ()
 5 @property (nonatomic,strong) NSMutableArray *studentArray;
 6 @property (nonatomic,strong) NSManagedObjectContext *mContext;
 7 @end
 8 static NSString *identifier = @"cell";
 9 @implementation StudentController
10 
11 - (void)viewDidLoad {
12     [super viewDidLoad];
13     AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
14     //获取数据管理器类
15     self.mContext = appDelegate.managedObjectContext;
16     
17     self.studentArray = [NSMutableArray arrayWithArray: self.loClass.studentRelation.allObjects];
18 }
19 
20 - (void)didReceiveMemoryWarning {
21     [super didReceiveMemoryWarning];
22     // Dispose of any resources that can be recreated.
23 }
24 
25 #pragma mark - Table view data source
26 
27 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
28 
29     return 1;
30 }
31 
32 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
33 
34     return self.studentArray.count;
35 }
36 
37 
38 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
39     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
40     
41     Student *stu = self.studentArray[indexPath.row];
42     cell.textLabel.text = stu.name;
43     
44     
45     return cell;
46 }
47 
48 
49 
50 // Override to support conditional editing of the table view.
51 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
52     // Return NO if you do not want the specified item to be editable.
53     return YES;
54 }
55 
56 
57 
58 // Override to support editing the table view.
59 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
60     if (editingStyle == UITableViewCellEditingStyleDelete) {
61         //创建查询请求
62         NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Student"];
63         //创建实体描述
64         NSEntityDescription *studentED = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:self.mContext];
65         //设置查询条件的实体属性
66         fetchRequest.entity = studentED;
67         //创建查询条件
68         Student *student = self.studentArray[indexPath.row];
69         NSString *name = student.name;
70         NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name = %@",name];
71         //设置查询请求的谓词属性
72         fetchRequest.predicate = predicate;
73         //创建排序器 NSSortDescription
74         NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
75         fetchRequest.sortDescriptors = @[sort];
76         NSArray *result = [self.mContext executeFetchRequest:fetchRequest error:nil];
77         for (Student *loClass in result) {
78             [self.mContext deleteObject:loClass];
79         }
80         [self.mContext save:nil];
81         [self.studentArray removeObjectAtIndex:indexPath.row];
82         [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
83     } else if (editingStyle == UITableViewCellEditingStyleInsert) {
84         // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
85     }   
86 }
87 
88 @end
posted @ 2016-03-15 20:02  恒远也  阅读(177)  评论(0编辑  收藏  举报