#import"viewController.h"
#import"AppDelegate.h"
#import"Student+CoreDataProperties.h"
// coreData 的同步过程:我们要对一份数据进行操作:
@interface ViewController ()
@property (nonatomic, strong) NSMutableArray *allDataArray;
@property (nonatomic, strong) UITableView *myTableView;
@end
@implementation ViewController
// 懒加载数组
-(NSMutableArray *)allDataArray{
if (!_allDataArray) {
_allDataArray = [NSMutableArray array];
}
return _allDataArray;
}
// 获得 appDelegate 代理对象
-(AppDelegate *) appDelegate{
return (AppDelegate *)[UIApplication sharedApplication].delegate;
}
// 获取被管理对象的上下文
-(NSManagedObjectContext *) managedObjectContext{
// 获得 application 的代理
AppDelegate *appDelegate = [self appDelegate];
// 获得被管理对象上下文
return appDelegate.managedObjectContext;
}
// 增加数据
-(void) addData{
// 测试插入 10条数据
for (int i = 0; i < 10; i++) {
// 获得实体描述对象 并创建数据类model
Student *stu = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:[self managedObjectContext]];
// 为被管理对象赋值
stu.name = [NSString stringWithFormat:@"呵呵%d",i];
stu.age = [NSNumber numberWithInt:22 + i]; // 实体对象的属性可以为对象类型
stu.number = [NSString stringWithFormat:@"%d",111 + i];
}
// 将操作完的数据存储到本地
[[self appDelegate] saveContext];
}
// 查询表中的数据
-(void)queryData{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:[self managedObjectContext]];
[fetchRequest setEntity:entity];
NSError *error = nil;
NSArray *fetchedObjects = [[self managedObjectContext] executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects == nil) {
NSLog(@"未获取到数据");
}else{
[self.allDataArray addObjectsFromArray:fetchedObjects];
[self.myTableView reloadData];
}
}
// 删除数据
-(void)deleteDataWithObject:(Student *)student{
if (student) {
[[self managedObjectContext]deleteObject:student];
}
// 将最新的数据同步到本地
[[self appDelegate] saveContext];
}
// 更新数据
-(void) updateDataWithStudent:(Student *)student{
// 更新 student 的 name 值
student.name = @"葫芦娃";
// 同步到本地
[[self appDelegate]saveContext];
}
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end