什么是 CoreData
它不是数据库!
通常用于数据库做为底层存储
也可以使用XML文件;
基本概念
Snip20160427_8.png创建模型
创建文件,重点吧use Data 打上勾
进入,添加entity
帮entity添加属性
创建HomeWork,添加剂对应属性
创建student,添加剂对应属性
设置关系
因为一个学生对应多个作业, 而不是 一个作业对应多个学生
to many
这里其实推荐做双线链接
可以选这不看表格 ,看关系图
Snip20160427_19.png
你的是不是这样呢?
Snip20160427_20.png生成文件
Snip20160427_23.png我们模型建立完毕 ,下面说说环境设置
//
// ViewController.m
// HelloCoreData
//
// Created by zhu on 16/4/27.
// Copyright © 2016年 zhu. All rights reserved.
//
#import "ViewController.h"
#import "Student.h"
#import "HomeWork.h"
#import "AppDelegate.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self setCoreData];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)setCoreData{
AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = [delegate managedObjectContext];
Student *personOne = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:context];
personOne.age = @15;
personOne.name = @"Jack";
HomeWork *HomeWorkOne = [NSEntityDescription insertNewObjectForEntityForName:@"HomeWork" inManagedObjectContext:context];
[HomeWorkOne setValue:@"EnglishHomeWrok" forKey:@"content"];
NSMutableSet *homeworks =[personOne.works mutableCopy];
[homeworks addObject:HomeWorkOne];
[personOne addWorks:homeworks];
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 100, 2000, 100)];
//来个大神帮我处理一下.如何便捷提出personOne的科目...
// label.text=(personOne的科目);
[self.view addSubview:label];
NSError *error = nil;
if(![context save:&error])
{
NSLog(@"不能保存:%@",[error localizedDescription]);
}else {
NSLog(@"新增成功");
}
//查询
NSFetchRequest *request = [ NSFetchRequest fetchRequestWithEntityName:@"Student"];
//排序(过滤名字用J开头的)
request.sortDescriptors =@[[NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES]];
request.predicate = [NSPredicate predicateWithFormat:@"age >%@",@"12"];
//
//执行
NSError *requestError= nil;
NSArray *objs = [context executeFetchRequest:request error:&requestError];
if (requestError) {
[NSException raise:@"@Qure failed" format:@"%@",[requestError localizedDescription]];
}
[self.view addSubview:label];
//遍历结果
for (_obj in objs) {
NSLog(@"====================================");
NSLog(@"name = %@",[_obj valueForKey:@"name"]);
NSLog(@"age = %@",[_obj valueForKey:@"age"]);
NSLog(@"works = %@",[_obj valueForKey:@"works"]);
NSLog(@"====================================");
}
}
@end
网友评论