Demo鏈接
1、CoreData的基本操作CRUD
//
// ViewController.m
// ScutCoreData
//
// Created by bwu on 16/5/19.
// Copyright ? 2016年 wubiao. All rights reserved.
//
#import "ViewController.h"
#import "Student.h"
#import "Student+CoreDataProperties.h"
#include <CoreData/CoreData.h>
/*
1.創(chuàng)建模型文件 [相當(dāng)于一個(gè)數(shù)據(jù)庫(kù)里的表]
2.添加實(shí)體 [一張表]
3.創(chuàng)建實(shí)體類(lèi) [相當(dāng)模型]
4.生成上下文 關(guān)聯(lián)模型文件生成數(shù)據(jù)庫(kù)
5、關(guān)聯(lián)的時(shí)候,如果本地沒(méi)有數(shù)據(jù)庫(kù)文件,Coreadata自己會(huì)創(chuàng)建
*/
@interface ViewController ()
@property(nonatomic,strong) NSManagedObjectContext *context;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// .xcdatamodeld文件相當(dāng)于數(shù)據(jù)庫(kù)文件,里面的實(shí)體(Entity)即是"表",一個(gè)數(shù)據(jù)庫(kù)中可以有多張表格
//1、創(chuàng)建上下文對(duì)象,對(duì)數(shù)據(jù)庫(kù)的所有操作都是通過(guò)對(duì)應(yīng)的上下文進(jìn)行操作的
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
//2、實(shí)例化模型文件(數(shù)據(jù)庫(kù)文件)
//mergedModelFromBundles這個(gè)方法傳入nil時(shí),會(huì)搜索工程項(xiàng)目中所有的.xcdatamodeld文件,并將這些文件中的所有表格放在一個(gè)數(shù)據(jù)庫(kù)。當(dāng)有多個(gè)數(shù)據(jù)庫(kù)時(shí)使用這個(gè)方法會(huì)造成數(shù)據(jù)的混亂
NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
//3、創(chuàng)建持久化存儲(chǔ)協(xié)調(diào)器,這個(gè)類(lèi)主要是關(guān)聯(lián)我的數(shù)據(jù)庫(kù)文件(模型文件\底層文件)
NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
//4、通過(guò)NSPersistentStoreCoordinator告訴Coredata數(shù)據(jù)庫(kù)的名字和路徑,并將它關(guān)聯(lián)上下文
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *sqlitePath = [doc stringByAppendingPathComponent:@"student.sqlite"];
NSLog(@"%@",sqlitePath);
NSError *error = nil;
[store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:&error];
context.persistentStoreCoordinator = store; //上下文就是通過(guò)持久化存儲(chǔ)協(xié)調(diào)器來(lái)修改底層文件保存的數(shù)據(jù)
self.context = context;
}
// 數(shù)據(jù)庫(kù)的操作 CURD Create Update Read Delete
#pragma mark 添加學(xué)生
-(IBAction)addStudent{
for (int i =0 ; i < 20; i++) {
//通過(guò)NSEntityDescription向?qū)嶓w(表)中插入數(shù)據(jù),這個(gè)方法返回__kindof NSManagedObject *實(shí)體類(lèi)(模型Model)
Student *student = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:self.context];
//設(shè)置實(shí)體類(lèi)的相關(guān)屬性
student.name =[NSString stringWithFormat:@"xiaoming%d",i];
student.height = @1.80;
student.brithday = [NSDate date];
// 直接保存數(shù)據(jù)庫(kù)
NSError *error = nil;
[_context save:&error];
if (error) {
NSLog(@"%@",error);
}
}
}
#pragma mark 讀取學(xué)生信息
-(IBAction)readStudent{
// 1.FectchRequest 抓取請(qǐng)求對(duì)象
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Student"];
// 2.設(shè)置過(guò)濾條件
// 查找zhangsan
NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",
@"xiaoming1"];
request.predicate = pre;
// 3.設(shè)置排序
// 身高的升序排序
NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO];
request.sortDescriptors = @[heigtSort];
// 4.執(zhí)行請(qǐng)求
NSError *error = nil;
NSArray *emps = [_context executeFetchRequest:request error:&error];
if (error) {
NSLog(@"error");
}
//NSLog(@"%@",emps);
//遍歷員工
for (Student *emp in emps) {
NSLog(@"名字 %@ 身高 %@ 生日 %@",emp.name,emp.height,emp.brithday);
}
}
#pragma mark 更新學(xué)生信息
-(IBAction)updateStudent{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Student"];
// 1.2設(shè)置過(guò)濾條件
// 查找xiaoming2
NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",
@"xiaoming2"];
request.predicate = pre;
// 1.3執(zhí)行請(qǐng)求
NSArray *emps = [_context executeFetchRequest:request error:nil];
// 2.更新身高
for (Student *e in emps) {
e.height = @2.0;
}
// 3.保存
[_context save:nil];
}
#pragma mark 刪除學(xué)生
-(IBAction)deleteStudent{
// 1.1FectchRequest 抓取請(qǐng)求對(duì)象
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Student"];
// 1.2設(shè)置過(guò)濾條件
// 查找xiaoming3
NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",
@"xiaoming3"];
request.predicate = pre;
// 1.3執(zhí)行請(qǐng)求
NSArray *emps = [_context executeFetchRequest:request error:nil];
// 2.刪除
for (Student *e in emps) {
[_context deleteObject:e];
}
// 3.保存
[_context save:nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
2、CoreData的多表進(jìn)行關(guān)聯(lián)
//
// ViewController.m
// ScutCoreData
//
// Created by bwu on 16/5/19.
// Copyright ? 2016年 wubiao. All rights reserved.
//
#import "ViewController.h"
#import "Student.h"
#import "Student+CoreDataProperties.h"
#import <CoreData/CoreData.h>
#import "Card.h"
#import "Card+CoreDataProperties.h"
/*
1.創(chuàng)建模型文件 [相當(dāng)于一個(gè)數(shù)據(jù)庫(kù)里的表]
2.添加實(shí)體 [一張表]
3.創(chuàng)建實(shí)體類(lèi) [相當(dāng)模型]
4.生成上下文 關(guān)聯(lián)模型文件生成數(shù)據(jù)庫(kù)
5、關(guān)聯(lián)的時(shí)候,如果本地沒(méi)有數(shù)據(jù)庫(kù)文件,Coreadata自己會(huì)創(chuàng)建
*/
@interface ViewController ()
@property(nonatomic,strong) NSManagedObjectContext *context;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// .xcdatamodeld文件相當(dāng)于數(shù)據(jù)庫(kù)文件,里面的實(shí)體(Entity)即是"表",一個(gè)數(shù)據(jù)庫(kù)中可以有多張表格
//1、創(chuàng)建上下文對(duì)象,對(duì)數(shù)據(jù)庫(kù)的所有操作都是通過(guò)對(duì)應(yīng)的上下文進(jìn)行操作的
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
//2、實(shí)例化模型文件(數(shù)據(jù)庫(kù)文件)
//mergedModelFromBundles這個(gè)方法傳入nil時(shí),會(huì)搜索工程項(xiàng)目中所有的.xcdatamodeld文件,并將這些文件中的所有表格放在一個(gè)數(shù)據(jù)庫(kù)。當(dāng)有多個(gè)數(shù)據(jù)庫(kù)時(shí)使用這個(gè)方法會(huì)造成數(shù)據(jù)的混亂
NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
//3、創(chuàng)建持久化存儲(chǔ)協(xié)調(diào)器,這個(gè)類(lèi)主要是關(guān)聯(lián)我的數(shù)據(jù)庫(kù)文件(模型文件\底層文件)
NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
//4、通過(guò)NSPersistentStoreCoordinator告訴Coredata數(shù)據(jù)庫(kù)的名字和路徑,并將它關(guān)聯(lián)上下文
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *sqlitePath = [doc stringByAppendingPathComponent:@"student.sqlite"];
NSLog(@"%@",sqlitePath);
NSError *error = nil;
[store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:&error];
context.persistentStoreCoordinator = store; //上下文就是通過(guò)持久化存儲(chǔ)協(xié)調(diào)器來(lái)修改底層文件保存的數(shù)據(jù)
self.context = context;
}
// 數(shù)據(jù)庫(kù)的操作 CURD Create Update Read Delete
#pragma mark 添加學(xué)生
-(IBAction)addStudent{
for (int i =10 ; i < 20; i++) {
Card *card = [NSEntityDescription insertNewObjectForEntityForName:@"Card" inManagedObjectContext:self.context];
card.no = @"wubiao";
//通過(guò)NSEntityDescription向?qū)嶓w(表)中插入數(shù)據(jù),這個(gè)方法返回__kindof NSManagedObject *實(shí)體類(lèi)(模型Model)
Student *student = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:self.context];
//設(shè)置實(shí)體類(lèi)的相關(guān)屬性
student.name =[NSString stringWithFormat:@"xiaoming%d",i];
student.height = @1.80;
student.brithday = [NSDate date];
// 設(shè)置Student和Card之間的關(guān)聯(lián)關(guān)系
student.card = card;
//card.student = student;
// 直接保存數(shù)據(jù)庫(kù)
NSError *error = nil;
[_context save:&error];
if (error) {
NSLog(@"%@",error);
}
}
}
#pragma mark 讀取學(xué)生信息
-(IBAction)readStudent{
// 1.FectchRequest 抓取請(qǐng)求對(duì)象
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Student"];
//
// // 2.設(shè)置過(guò)濾條件
//
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"card.no = %@",@"wubiao"];
request.predicate = predicate;
// 3.設(shè)置排序
// 身高的升序排序
NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO];
request.sortDescriptors = @[heigtSort];
// 4.執(zhí)行請(qǐng)求
NSError *error = nil;
NSArray *emps = [_context executeFetchRequest:request error:&error];
if (error) {
NSLog(@"error");
}
//NSLog(@"%@",emps);
//遍歷員工
for (Student *emp in emps) {
NSLog(@"名字 %@ 身高 %@ 生日 %@ 身份證號(hào)碼%@",emp.name,emp.height,emp.brithday,emp.card);
}
}
#pragma mark 更新學(xué)生信息
-(IBAction)updateStudent{
}
#pragma mark 刪除學(xué)生
-(IBAction)deleteStudent{
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
3、CoreData的多個(gè)數(shù)據(jù)庫(kù)的操作
/*
1.創(chuàng)建模型文件 [相當(dāng)于一個(gè)數(shù)據(jù)庫(kù)里的表]
2.添加實(shí)體 [一張表]
3.創(chuàng)建實(shí)體類(lèi) [相當(dāng)模型]
4.生成上下文 關(guān)聯(lián)模型文件生成數(shù)據(jù)庫(kù)
5、關(guān)聯(lián)的時(shí)候,如果本地沒(méi)有數(shù)據(jù)庫(kù)文件,Coreadata自己會(huì)創(chuàng)建
*/
@interface ViewController ()
@property(nonatomic,strong) NSManagedObjectContext *context;
@property(nonatomic,strong) NSManagedObjectContext *studentContext;
@property(nonatomic,strong) NSManagedObjectContext *weiboContext;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 一個(gè)數(shù)據(jù)庫(kù)對(duì)應(yīng)一個(gè)上下文
_studentContext = [self setupContextWithModelName:@"Student"];
_weiboContext = [self setupContextWithModelName:@"Weibo"];
}
-(NSManagedObjectContext *)setupContextWithModelName:(NSString *)modelName
{
// .xcdatamodeld文件相當(dāng)于數(shù)據(jù)庫(kù)文件,里面的實(shí)體(Entity)即是"表",一個(gè)數(shù)據(jù)庫(kù)中可以有多張表格
//1、創(chuàng)建上下文對(duì)象,對(duì)數(shù)據(jù)庫(kù)的所有操作都是通過(guò)對(duì)應(yīng)的上下文進(jìn)行操作的
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
//2、實(shí)例化模型文件(數(shù)據(jù)庫(kù)文件)
//2.1mergedModelFromBundles這個(gè)方法傳入nil時(shí),會(huì)搜索工程項(xiàng)目中所有的.xcdatamodeld文件,并將這些文件中的所有表格放在一個(gè)數(shù)據(jù)庫(kù)。當(dāng)有多個(gè)數(shù)據(jù)庫(kù)時(shí)使用這個(gè)方法會(huì)造成數(shù)據(jù)的混亂
// NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
NSLog(@"%@",[[NSBundle mainBundle] bundlePath]);
//2.2當(dāng)工程項(xiàng)目中有多個(gè)數(shù)據(jù)庫(kù)時(shí) 要使用這個(gè)方法來(lái)實(shí)例化模型文件。這樣可以將不同的數(shù)據(jù)庫(kù)分開(kāi),而且不同的數(shù)據(jù)庫(kù)對(duì)應(yīng)不同的上下文
NSURL *companyURL = [[NSBundle mainBundle] URLForResource:modelName withExtension:@"momd"];
NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:companyURL];
//3、創(chuàng)建持久化存儲(chǔ)協(xié)調(diào)器,這個(gè)類(lèi)主要是關(guān)聯(lián)我的數(shù)據(jù)庫(kù)文件(模型文件\底層文件)
NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
//4、通過(guò)NSPersistentStoreCoordinator告訴Coredata數(shù)據(jù)庫(kù)的名字和路徑,并將它關(guān)聯(lián)上下文
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *sqliteName = [NSString stringWithFormat:@"%@.sqlite",modelName];
NSString *sqlitePath = [doc stringByAppendingPathComponent:sqliteName];
NSLog(@"%@",sqlitePath);
NSError *error = nil;
[store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:&error];
context.persistentStoreCoordinator = store; //上下文就是通過(guò)持久化存儲(chǔ)協(xié)調(diào)器來(lái)修改底層文件保存的數(shù)據(jù)
return context;
}
// 數(shù)據(jù)庫(kù)的操作 CURD Create Update Read Delete
#pragma mark 添加學(xué)生
-(IBAction)addStudent{
//通過(guò)NSEntityDescription向?qū)嶓w(表)中插入數(shù)據(jù),這個(gè)方法返回__kindof NSManagedObject *實(shí)體類(lèi)(模型Model)
Student *student = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:_studentContext];
//設(shè)置實(shí)體類(lèi)的相關(guān)屬性
student.name =@"xiaoming";
student.height = @1.80;
student.brithday = [NSDate date];
// 直接保存數(shù)據(jù)庫(kù)
NSError *error = nil;
[_studentContext save:&error];
if (error) {
NSLog(@"%@",error);
}
// 發(fā)微博
Status *status =[NSEntityDescription insertNewObjectForEntityForName:@"Status" inManagedObjectContext:_weiboContext];
status.text = @"畢業(yè),挺激動(dòng)";
[_weiboContext save:nil];
}