CoreData的簡單使用sql
一.單表簡單操做數據庫
1.建立模型文件 [至關於一個數據庫裏的表]app
2.添加實體 [一張表]fetch
3.建立實體類 [至關模型]spa
4.生成上下文 關聯模型文件生成數據庫orm
/*sqlite
* 關聯的時候,若是本地沒有數據庫文件,Coreadata本身會建立對象
*/排序
// 上下文索引
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
// 上下文關連數據庫
// model模型文件
NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
// 持久化存儲調度器
// 持久化,把數據保存到一個文件,而不是內存
NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
// 告訴Coredata數據庫的名字和路徑
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *sqlitePath = [doc stringByAppendingPathComponent:@"company.sqlite"];
NSLog(@"%@",sqlitePath);
[store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:nil];
context.persistentStoreCoordinator = store;
_context = context;
5.對數據作增刪查改操做
A.添加員工
-(void)addEmployee{
// 建立一個員工對象
//Employee *emp = [[Employee alloc] init];
Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context];
emp.name = @"wangwu";
emp.height = @1.80;
emp.birthday = [NSDate date];
// 直接保存數據庫
NSError *error = nil;
[_context save:&error];
if (error) {
NSLog(@"%@",error);
}
}
#pragma mark 讀取員工
-(void)readEmployee{
// 1.FectchRequest 抓取請求對象
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
// 2.設置過濾條件
// 查找zhangsan
NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",
@"zhangsan"];
//request.predicate = pre;
// 3.設置排序
// 身高的升序排序
NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO];
request.sortDescriptors = @[heigtSort];
// 4.執行請求
NSError *error = nil;
NSArray *emps = [_context executeFetchRequest:request error:&error];
if (error) {
NSLog(@"error");
}
//NSLog(@"%@",emps);
//遍歷員工
for (Employee *emp in emps) {
NSLog(@"名字 %@ 身高 %@ 生日 %@",emp.name,emp.height,emp.birthday);
}
}
#pragma mark 更新員工
-(void)updateEmployee{
// 改變zhangsan的身高爲2m
// 1.查找到zhangsan
// 1.1FectchRequest 抓取請求對象
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
// 1.2設置過濾條件
// 查找zhangsan
NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",
@"zhangsan"];
request.predicate = pre;
// 1.3執行請求
NSArray *emps = [_context executeFetchRequest:request error:nil];
// 2.更新身高
for (Employee *e in emps) {
e.height = @2.0;
}
// 3.保存
[_context save:nil];
}
#pragma mark 刪除員工
-(void)deleteEmployee{
// 刪除 lisi
// 1.查找lisi
// 1.1FectchRequest 抓取請求對象
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
// 1.2設置過濾條件
// 查找zhangsan
NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",
@"lisi"];
request.predicate = pre;
// 1.3執行請求
NSArray *emps = [_context executeFetchRequest:request error:nil];
// 2.刪除
for (Employee *e in emps) {
[_context deleteObject:e];
}
// 3.保存
[_context save:nil];
}
二.多表關聯查詢和操做
//
// ViewController.m
// 01.CoreData的簡單使用
//
// Created by apple on 14/12/5.
// Copyright (c) 2014年 heima. All rights reserved.
//
#import "ViewController.h"
#import <CoreData/CoreData.h>
#import "Employee.h"
@interface ViewController (){
NSManagedObjectContext *_context;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// 1.建立模型文件 [至關於一個數據庫裏的表]
// 2.添加實體 [一張表]
// 3.建立實體類 [至關模型]
// 4.生成上下文 關聯模型文件生成數據庫
/*
* 關聯的時候,若是本地沒有數據庫文件,Coreadata本身會建立
*/
// 上下文
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
// 上下文關連數據庫
// model模型文件
NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
// 持久化存儲調度器
// 持久化,把數據保存到一個文件,而不是內存
NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
// 告訴Coredata數據庫的名字和路徑
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *sqlitePath = [doc stringByAppendingPathComponent:@"company.sqlite"];
NSLog(@"%@",sqlitePath);
[store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:nil];
context.persistentStoreCoordinator = store;
_context = context;
}
// 數據庫的操做 CURD Create Update Read Delete
#pragma mark 添加員工
-(IBAction)addEmployee{
// 建立一個員工對象
//Employee *emp = [[Employee alloc] init];
for (int i = 0; i < 15; i++) {
Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context];
emp.name = [NSString stringWithFormat:@"wangwu%d",i];
emp.height = @(1.80 + i);
emp.birthday = [NSDate date];
}
// 直接保存數據庫
NSError *error = nil;
[_context save:&error];
if (error) {
NSLog(@"%@",error);
}
}
#pragma mark 讀取員工
-(IBAction)readEmployee{
// 1.FectchRequest 抓取請求對象
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
// 3.設置排序
// 身高的升序排序
NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO];
request.sortDescriptors = @[heigtSort];
// 模糊查詢
// 名字以"wang"開頭
// NSPredicate *pre = [NSPredicate predicateWithFormat:@"name BEGINSWITH %@",@"wangwu1"];
// request.predicate = pre;
// 名字以"1"結尾
// NSPredicate *pre = [NSPredicate predicateWithFormat:@"name ENDSWITH %@",@"1"];
// request.predicate = pre;
// 名字包含"wu1"
// NSPredicate *pre = [NSPredicate predicateWithFormat:@"name CONTAINS %@",@"wu1"];
// request.predicate = pre;
// like
//以wangwu1*開頭
NSPredicate *pre = [NSPredicate predicateWithFormat:@"name like %@",@"*wu12"];
request.predicate = pre;
// 4.執行請求
NSError *error = nil;
NSArray *emps = [_context executeFetchRequest:request error:&error];
if (error) {
NSLog(@"error");
}
//NSLog(@"%@",emps);
//遍歷員工
for (Employee *emp in emps) {
NSLog(@"名字 %@ 身高 %@ 生日 %@",emp.name,emp.height,emp.birthday);
}
}
#pragma mark 分頁查詢
-(void)pageSeacher{
// 1.FectchRequest 抓取請求對象
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
// 3.設置排序
// 身高的升序排序
NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO];
request.sortDescriptors = @[heigtSort];
// 總有共有15數據
// 每次獲取6條數據
// 第一頁 0,6
// 第二頁 6,6
// 第三頁 12,6 3條數據
// 分頁查詢 limit 0,5
// 分頁的起始索引
request.fetchOffset = 12;
// 分頁的條數
request.fetchLimit = 6;
// 4.執行請求
NSError *error = nil;
NSArray *emps = [_context executeFetchRequest:request error:&error];
if (error) {
NSLog(@"error");
}
//NSLog(@"%@",emps);
//遍歷員工
for (Employee *emp in emps) {
NSLog(@"名字 %@ 身高 %@ 生日 %@",emp.name,emp.height,emp.birthday);
}
}
@end
三.多個數據庫的查詢
#import "ViewController.h"
#import <CoreData/CoreData.h>
#import "Employee.h"
#import "Status.h"
@interface ViewController ()
{
NSManagedObjectContext *_context;
NSManagedObjectContext *_companyContext;
NSManagedObjectContext *_weiboContext;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// 一個數據庫對應一個上下文
_companyContext = [self setupContextWithModelName:@"Company"];
_weiboContext = [self setupContextWithModelName:@"Weibo"];
//_context = context;
}
/**
* 根據模型文件,返回一個上下文
*/
-(NSManagedObjectContext *)setupContextWithModelName:(NSString *)modelName{
// 1.建立模型文件 [至關於一個數據庫裏的表]
// 2.添加實體 [一張表]
// 3.建立實體類 [至關模型]
// 4.生成上下文 關聯模型文件生成數據庫
/*
* 關聯的時候,若是本地沒有數據庫文件,Coreadata本身會建立
*/
// 上下文
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
// 上下文關連數據庫
// model模型文件
// 使用下面的方法,若是 bundles爲nil 會把bundles裏面的全部模型文件的表放在一個數據庫
//NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
NSLog(@"%@",[[NSBundle mainBundle] bundlePath]);
NSURL *companyURL = [[NSBundle mainBundle] URLForResource:modelName withExtension:@"momd"];
NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:companyURL];
// 持久化存儲調度器
// 持久化,把數據保存到一個文件,而不是內存
NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
// 告訴Coredata數據庫的名字和路徑
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *sqliteName = [NSString stringWithFormat:@"%@.sqlite",modelName];
NSString *sqlitePath = [doc stringByAppendingPathComponent:sqliteName];
NSLog(@"%@",sqlitePath);
[store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:nil];
context.persistentStoreCoordinator = store;
return context;
}
// 數據庫的操做 CURD Create Update Read Delete
#pragma mark 添加員工
-(IBAction)addEmployee{
// 添加員工
Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_companyContext];
emp.name = @"zhagsan";
emp.height = @2.3;
emp.birthday = [NSDate date];
// 直接保存數據庫
NSError *error = nil;
[_companyContext save:&error];
if (error) {
NSLog(@"%@",error);
}
// 發微博
Status *status =[NSEntityDescription insertNewObjectForEntityForName:@"Status" inManagedObjectContext:_weiboContext];
status.text = @"畢業,挺激動";
status.createDate = [NSDate date];
[_weiboContext save:nil];
}
#pragma mark 讀取員工
-(IBAction)readEmployee
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
// 4.執行請求
NSError *error = nil;
NSArray *emps = [_companyContext executeFetchRequest:request error:&error];
if (error) {
NSLog(@"error");
}
//NSLog(@"%@",emps);
//遍歷員工
for (Employee *emp in emps) {
NSLog(@"名字 %@ 身高 %@ 生日 %@",emp.name,emp.height,emp.birthday);
}
}
@end