1.
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
NSLog(@"%@",NSTemporaryDirectory());//找coredata 路径
//第一种
//实体描述
NSEntityDescription *entityD = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.managedObjectContext];
Person *person = [[Person alloc]initWithEntity:entityD insertIntoManagedObjectContext:self.managedObjectContext];
person.name = @"高富帅";
person.age = @(100);
[self saveContext];//保存
//第二种
//创建一个对象 即添加
Person *sbian = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.managedObjectContext];
sbian.name = @"邸伟男";
sbian.age = @(12);
[self saveContext];
//查找
NSFetchRequest *fetchReq = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
//谓词筛选
fetchReq.predicate = [NSPredicate predicateWithFormat:@"name = '高富帅' AND age > 12"]; //搜索的关键词
// fetchReq.sortDescriptors //排序
NSArray *arr = [self.managedObjectContext executeFetchRequest:fetchReq error:nil];
NSLog(@"%@",arr);
//修改对象 即修改
Person *suibian2 = arr[0];
suibian2.name = @"高富帅2";
[self saveContext];
//删除对象 即删除
[self.managedObjectContext deleteObject:suibian2];
//删除哪一行先查后删
[self saveContext];
//找到数据管理器
// AppDelegate *appdel = [(AppDelegate *)[UIApplication sharedApplication].delegate ;
// appdel.managedObjectContext
//
return YES;
2.
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
//数据管理类
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
//数据模型
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
//数据连接器
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;
.M
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
RootViewController.h
@interface RootViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
RootViewController.m
#import "RootViewController.h"
#import "StudentViewController.h"
#import "AppDelegate.h"
#import "Class15.h"
#import "Student.h"
#import "Teacher.h"
@interface RootViewController ()
//数据管理类
@property (nonatomic, strong) NSManagedObjectContext *managedObjectContext;
//数据数组
@property (nonatomic, strong) NSMutableArray *allClass;
//显示视图
@property (nonatomic, strong) UITableView *tableView;
@end
@implementation RootViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
// self.allClass = [[NSMutableArray alloc] initWithCapacity:0];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addAction)];
//取出AppDelegate的指针
AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
//指向数据管理器
self.managedObjectContext = appDelegate.managedObjectContext;
数组初始化 用于显示
self.allClass = [NSMutableArray array];
// 获取数据库中的数据
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Class15"];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
[fetchRequest setSortDescriptors:@[sortDescriptor]]; // 设置查询的排序方式
// 检索
NSError *error;
//查找取出全部数据
NSArray *allClassArray = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
//报错处理
if (!error) {
[self.allClass setArray:allClassArray];
}else{
NSLog(@"检索失败: Error = %@", error);
}
self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
self.tableView.delegate = self;
self.tableView.dataSource = self;
[self.view addSubview:_tableView];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return self.allClass.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellId = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
}
// 代码保护
if ([self.allClass count]) {
Class15 *classEntity = [self.allClass objectAtIndex:indexPath.row];
cell.textLabel.text = classEntity.name;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
StudentViewController *classInfo = [[StudentViewController alloc] init];
classInfo.lanouClass = [self.allClass objectAtIndex:indexPath.row]; // 传递class到下个界面
[self.navigationController pushViewController:classInfo animated:YES];
}
- (void)addAction
{
// 创建一个实体描述
NSEntityDescription *classED = [NSEntityDescription entityForName:@"Class15" inManagedObjectContext:self.managedObjectContext];
Class15 *classEntity = [[Class15 alloc] initWithEntity:classED insertIntoManagedObjectContext:self.managedObjectContext];
NSInteger classNumber = arc4random() % 1000 + 1;
classEntity.name = [NSString stringWithFormat:@"DLS%ld", (long)classNumber];
// 添加班级老师和学生
//添加老师
NSEntityDescription *teacherED = [NSEntityDescription entityForName:@"Teacher" inManagedObjectContext:self.managedObjectContext];
classEntity.teacher = [[Teacher alloc] initWithEntity:teacherED insertIntoManagedObjectContext:self.managedObjectContext];
int teacherNumber = arc4random() % 20000 + 100;
classEntity.teacher.name = [NSString stringWithFormat:@"中仁%d", teacherNumber];
classEntity.teacher.course = @"UI";
//随机学生数
int studentNumber = arc4random() % 6 + 5;
for (int i = 0; i < studentNumber; i ++) {
NSEntityDescription *stdentED = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:self.managedObjectContext];
Student *studentEntity = [[Student alloc] initWithEntity:stdentED insertIntoManagedObjectContext:self.managedObjectContext];
studentEntity.name = [NSString stringWithFormat:@"zhangsan%d", i];
studentEntity.age = [NSNumber numberWithInt:arc4random() % 7 + 18];
[classEntity addStudentObject:studentEntity]; // 学生和班级建立关联
[classEntity.teacher addStudentObject:studentEntity]; // 学生和老师建立关联
}
// 声明一个NSError,查看保存是否成功
NSError *error;
[self.managedObjectContext save:&error];
if (!error) {
[self.allClass addObject:classEntity]; // 往数组中添加实体的一个实例,相当于数据库中的一条数据
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.allClass.count - 1 inSection:0];
[self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
}else{
NSLog(@"数据插入失败:Error = %@", error);
}
}
StudentViewController.h
@class Class15;
@interface StudentViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) Class15 *lanouClass;
StudentViewController.m
#import "Teacher.h"
#import "Class15.h"
#import "Student.h"
#import "AppDelegate.h"
@interface StudentViewController ()
@property (nonatomic, strong) NSManagedObjectContext *managedObjectContext; // 数据管理类
@property (nonatomic, strong) NSMutableArray *allStudents; // 当前班级的所有学生
@property (nonatomic, strong) Teacher *classTeacher; // 当前班级的老师
@end
@implementation StudentViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
// 初始化学生数组
self.allStudents = [NSMutableArray array];
self.managedObjectContext = ((AppDelegate *)[UIApplication sharedApplication].delegate).managedObjectContext; // 得到被管理对象的上下文
// 取得当前班级的所有学生
NSFetchRequest *studentFetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Student"];
// 通过谓词来添加约束条件
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"class15=%@", self.lanouClass];
studentFetchRequest.predicate = predicate;
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
[studentFetchRequest setSortDescriptors:@[sortDescriptor]];
NSError *error;
NSArray *allStudentArray = [self.managedObjectContext executeFetchRequest:studentFetchRequest error:&error];
if (!error) {
[self.allStudents setArray:allStudentArray];
}else{
NSLog(@"查询出错: Error = %@", error);
}
// 取得当前班级的老师
NSFetchRequest *teacherFetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Teacher"];
// 通过谓词来添加约束条件
NSPredicate *teacherPredicate = [NSPredicate predicateWithFormat:@"class15 = %@", self.lanouClass];
teacherFetchRequest.predicate = teacherPredicate;
NSError *teacherError;
NSArray *allTeacherArray = [self.managedObjectContext executeFetchRequest:teacherFetchRequest error:&teacherError];
NSLog(@"teacherCount = %lu", (unsigned long)allTeacherArray.count);
self.classTeacher = [allTeacherArray firstObject];
UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
tableView.delegate = self;
tableView.dataSource = self;
[self.view addSubview:tableView];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return self.allStudents.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellId = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
}
// Configure the cell...
if (self.allStudents.count) {
Student *studentEntity = [self.allStudents objectAtIndex:indexPath.row];
NSLog(@"%@---%@",studentEntity.teacher,studentEntity.class);
cell.textLabel.text = [NSString stringWithFormat:@"学生是:%@ 老师:%@", studentEntity.name, self.classTeacher.name];
}
return cell;
}