zoukankan      html  css  js  c++  java
  • CoreData-03-系统自带CoreData

    //
    //  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
    时光见证了成长,还很无知,我想一点点幼稚转为有知!
  • 相关阅读:
    关于hibernate中多对多关系
    选择排序
    Offer是否具有法律效力?
    textarea文本域宽度和高度(width、height)自己主动适应变化处理
    序列相关的趣题 之三
    windows的定时任务设置
    Maven pom.xml 配置详解
    PS 图像特效-非线性滤波器
    PS 滤镜算法原理——拼贴
    PS 滤镜算法原理——曝光过度
  • 原文地址:https://www.cnblogs.com/foreveriOS/p/5459592.html
Copyright © 2011-2022 走看看