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
    时光见证了成长,还很无知,我想一点点幼稚转为有知!
  • 相关阅读:
    BootStrap Validator 版本差异问题导致的submitHandler失效问题的解决方法
    Xiaocms 去版权
    nodejs学习8:windows连接mongodb出现的错误解决办法
    gulp运行步骤
    电脑日常技巧:没有语言栏,怎么办???
    jquery中使用each遍历。
    一、Java基礎(二)
    一、Java基础(一)
    《JAVA编程思想》第四版 PDF
    TCP、UDP详解与抓包工具使用
  • 原文地址:https://www.cnblogs.com/foreveriOS/p/5459592.html
Copyright © 2011-2022 走看看