//
// ViewController.m
// schcoredatasqlite
//
// Created by tianshangrenjian on 15/6/25.
// Copyright © 2015年 tianshangrenjian. All rights reserved.
//
#import "ViewController.h"
#import "Student+CoreDataProperties.h"
@interface ViewController ()
@property (strong,nonatomic) NSManagedObjectContext *ctx;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//
//创建模型
NSManagedObjectModel *model=[NSManagedObjectModel mergedModelFromBundles:nil];
//创建持久化器
NSPersistentStoreCoordinator *persist=[[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
NSString *path=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSURL *url1=[NSURL fileURLWithPath:[path stringByAppendingPathComponent:@"stu.sqlite"]];
NSLog(@"%@",[path stringByAppendingPathComponent:@"stu.sqlite"]);
// [persist persistentStoreForURL:url1];
//告诉持久化器,当前保存的数据类型
[persist addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url1 options:nil error:nil];
//创建对象上下文,模型数据和数据库之间的桥梁
self.ctx=[[NSManagedObjectContext alloc] initWithConcurrencyType:NSManagedObjectExternalRelationshipError];
//设置上下文存储数据时所使用的持久化器
self.ctx.persistentStoreCoordinator=persist;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)btnadd:(id)sender {
//根据模型说明在上下文中,创建一个该模型的对象
Student *stu=[NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:self.ctx];
stu.name=@"bbc";
stu.gender=@"man";
stu.age=@"20";
[self.ctx save:nil];
[self selectStudent];
}
- (void)selectStudent
{
NSFetchRequest *request=[NSFetchRequest fetchRequestWithEntityName:@"Student"];
NSArray *array=[self.ctx executeFetchRequest:request error:nil];
for (Student *stu in array) {
NSLog(@"%@ %@ %@",stu.name,stu.gender,stu.age);
}
}
- (IBAction)btnchange:(id)sender {
NSFetchRequest *request=[NSFetchRequest fetchRequestWithEntityName:@"Student"];
NSPredicate *p=[NSPredicate predicateWithFormat:@"gender=%@",@"man"];
request.predicate=p;
NSArray *array=[self.ctx executeFetchRequest:request error:nil];
Student *stu=[array firstObject];
stu.name=@"fuckyou";
[self.ctx save:nil];
[self selectStudent];
}
- (IBAction)btnDel:(id)sender {
[self selectStudent];
NSFetchRequest *request=[NSFetchRequest fetchRequestWithEntityName:@"Student"];//select * from student
//查询条件过滤
NSPredicate *p=[NSPredicate predicateWithFormat:@"gender=%@",@"man"];//where gender='feman'
request.predicate=p;//select * from student where gender='feman'
NSArray *array=[self.ctx executeFetchRequest:request error:nil];
if (array==nil) {
return;
}
//删除查询结果中的第一个行
[self.ctx deleteObject:[array firstObject]];
//删除完毕之后必须保存,否则结果不不放回数据库
[self.ctx save:nil];
NSLog(@"begin delete:");
[self selectStudent];
}
@end