码迷,mamicode.com
首页 > 其他好文 > 详细

CoreData-03-系统自带CoreData

时间:2016-05-04 20:50:56      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

//
//  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

 

CoreData-03-系统自带CoreData

标签:

原文地址:http://www.cnblogs.com/foreveriOS/p/5459592.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!