coreData
//数据模型实体类的写法
#import <CoreData/CoreData.h>//.h
@interface Student : NSManagedObject
@property (nonatomic, copy)NSString *name;
@property (nonatomic, retain)NSNumber *age;
@end
#import "Person.h”//.m
@implementation Person
@dynamic name;
@dynamic age;
@end
//加载托管对象模型(coreData数据模型文件。)
NSString *momdPath = [[NSBundle mainBundle]pathForResource:@"Person" ofType:@"momd"];
NSManagedObjectModel *mom = [[NSManagedObjectModel alloc]initWithContentsOfURL:[NSURL fileURLWithPath:momdPath]];
//创建持久化存储协调器,处理数据的读写
NSPersistentStoreCoordinator *storeCoordinator = [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:mom];
//指定sqlite数据库文件的存储路径(coreData使用的数据库文件后缀一般写sqlite)
NSString *dbPath = [NSHomeDirectory() stringByAppendingString:@"/Documents/test.sqlite"];
//将coreData文件映射到数据库,并判断操作状态
NSError *createError = nil;
NSPersistentStore *store = [storeCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:dbPath] options:nil error:&createError];
if (!store) {//出错,打印错误信息localizedDescription
NSLog(@"add error: %@", createError.description);
}
//创建操作数据的对象()
_managedObjectContext = [[NSManagedObjectContext alloc]init];
//关联持久化存储协调器
_managedObjectContext.persistentStoreCoordinator = storeCoordinator;
/*增*/
//在数据库中插入一个实体(模型)
Person *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:_managedObjectContext];
//对实体的属性赋值
person.name = _textName.text;
person.age = [NSNumber numberWithInteger:_textAge.text.integerValue];
//把插入的实体保存到数据库中
NSError *insertError = nil;
if (![_managedObjectContext save:&insertError]) {
NSLog(@"insert error: %@", insertError.description);
} else {//插入成功
[_persons addObject:person];
[_tableV reloadData];
}
//删除
if (_persons.count > 0) {//确保有数据才删除
Person *person = _persons[_currentRow];
//从数据库中删除并保存
[_managedObjectContext deleteObject:person];
NSError *saveError = nil;
if (![_managedObjectContext save:&saveError]) {
NSLog(@"delete save error: %@", saveError.description);
} else {
//从本地数组中删除
[_persons removeObject:person];
[_tableV reloadData];
}
}
//修改
Person *person = _persons[_currentRow];
//先修改对象的属性
person.name = _textName.text;
person.age = [NSNumber numberWithInteger: _textAge.text.integerValue];
//再存入数据库
NSError *updateError = nil;
if (![_managedObjectContext save:&updateError]) {//保存失败
NSLog(@"update save error: %@", updateError.description);
} else {//保存成功
[_tableV reloadData];
}
//查
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
//定义查询条件的谓词(加*号的意思是以zh开头)
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like %@", @"zh*"];
//设置fetchRequest的谓词//如果不设查询条件会查询所有
[fetchRequest setPredicate:predicate];
//执行查询
NSArray *fetchResult = [_managedObjectContext executeFetchRequest:fetchRequest error:nil];
[_persons setArray:fetchResult];
[_tableV reloadData];
#import "ViewController.h"
#import "Student.h"
#define k_entity_student @"Student"
@interface ViewController () <UITableViewDataSource, UITableViewDelegate>
{
NSMutableArray *_dataArr;
NSManagedObjectContext *_moc;
NSInteger _currentRow;
}
@property (weak, nonatomic) IBOutlet UITextField *nameTF;
@property (weak, nonatomic) IBOutlet UITextField *age;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_dataArr = [[NSMutableArray alloc] init];
_currentRow = -1;
//找到coreData文件的路径,注意后缀需要用momd
NSString *path = [[NSBundle mainBundle] pathForResource:@"Person" ofType:@"momd"];
//目标对象模型
NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path]];
//需要绑定的数据库路径
NSString *sqlPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Person.sqlite"];
//持久化存储协调器
NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
NSError *error = nil;
//将对应Person的协调器,和一个数据库关联起来
//NSPersistentStore存在的作用就是判断是否关联成功
NSPersistentStore *store = [coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlPath] options:nil error:&error];
//如果失败,打印错误信息
if (!store) {
NSLog(@"store error = %@",error);
}
//目标对象上下文,(用来管理对象)
_moc = [[NSManagedObjectContext alloc] init];
//将协调器设置给上下文(上下文就是数据的管理者)
_moc.persistentStoreCoordinator = coordinator;
/*********环境搭建完毕,准备起飞************/
//创建一个查询请求,(针对Student)
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:k_entity_student];
//执行查询请求,返回结果是所有的实体对象
NSArray *resultArr = [_moc executeFetchRequest:request error:&error];
if (error) {
NSLog(@"fetch error = %@",error);
} else {
_dataArr.array = resultArr;
}
}
- (IBAction)btnClick:(UIButton *)sender
{
[self.view endEditing:YES];
NSError *error = nil;
switch (sender.tag) {
case 1:
{
//插入一个实体,返回值就是这个实体的对象指针
Student *dent = [NSEntityDescription insertNewObjectForEntityForName:k_entity_student inManagedObjectContext:_moc];
//修改内容
dent.name = _nameTF.text;
dent.age = [NSNumber numberWithInt:_age.text.intValue];
//保存并且判断是否成功(增删改的操作都需要保存)
if ([_moc save:&error]) {
[_dataArr addObject:dent];
[_tableView reloadData];
} else {
NSLog(@"insert error = %@",error);
}
}
break;
case 2:
{
if (_currentRow<0) {
return;
}
//找到需要删除的对象
Student *dent = _dataArr[_currentRow];
//删除
[_moc deleteObject:dent];
//保存并且判断是否成功
if ([_moc save:&error]) {
[_dataArr removeObjectAtIndex:_currentRow];
[_tableView reloadData];
} else {
NSLog(@"delete error = %@",error);
}
}
break;
case 3:
{
if (_currentRow<0) {
return;
}
Student *dent = _dataArr[_currentRow];
//修改
dent.name = _nameTF.text;
dent.age = [NSNumber numberWithInt:_age.text.intValue];
if ([_moc save:&error]) {
[_tableView reloadData];
} else {
NSLog(@"update error = %@",error);
}
}
break;
case 4:
{
//查询请求
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:k_entity_student];
//请求条件,*号是通配符
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like %@",[NSString stringWithFormat:@"%@*",_nameTF.text]];
request.predicate = predicate;
_dataArr.array = [_moc executeFetchRequest:request error:nil];
[_tableView reloadData];
}
break;
default:
break;
}
_currentRow = -1;
}
#pragma mark - tableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _dataArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 60;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"qqq"];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"qqq"];
}
Student *dent = _dataArr[indexPath.row];
cell.textLabel.text = dent.name;
cell.detailTextLabel.text = [NSString stringWithFormat:@"%@",dent.age];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
_currentRow = indexPath.row;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.view endEditing:YES];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
[self.view endEditing:YES];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end