// // ViewController.m // 02-CoreData-系统自带CoreData // // Created by mac on 16/5/4. // Copyright © 2016年 mac. All rights reserved. // #import "ViewController.h" #import "Student.h" #import "LYHClass.h" #import "AppDelegate.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self creatData]; NSLog(@"%@", NSHomeDirectory()); } - (void)creatData { NSLog(@"%@", NSHomeDirectory()); AppDelegate *appDelegate = [UIApplication sharedApplication].delegate; //1. 存储学生数据 //创建LYHClass对象 LYHClass *lyhClass = [NSEntityDescription insertNewObjectForEntityForName:@"LYHClass" inManagedObjectContext:appDelegate.managedObjectContext]; lyhClass.class_name = @"HZ88"; // lyhClass.student_count = @30; //2. 创建Student对象 for (int i = 0; i < 10; i ++) { Student *student = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:appDelegate.managedObjectContext]; student.name = [NSString stringWithFormat:@"stu_%i", i]; student.age = @(10 + i); //3. 添加到班级中 [lyhClass addStudentsObject:student]; } lyhClass.student_count = [NSNumber numberWithUnsignedInteger:lyhClass.students.count]; //4. 存储到文件 [appDelegate.managedObjectContext save:nil]; [self setupData:appDelegate]; } - (void)setupData:(AppDelegate *)appDelegate { //1. 读取数据 NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"LYHClass"]; //2. 设置筛选条件 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"class_name=‘HZ90‘;"]; request.predicate = predicate; //3. 执行筛选 NSArray *array = [appDelegate.managedObjectContext executeFetchRequest:request error:nil]; LYHClass *lyhClass = [array firstObject]; //4. 获取全班学生的集合 NSSet *students = lyhClass.students; for (Student *stu in students) { NSLog(@"学生姓名:%@,年龄:%@", stu.name, stu.age); } } @end
时间: 2024-10-25 04:44:02