首先创建一个CoreData工程,这样就配置出了CoreData工程,系统会自动生成方法。添加需要添加的实例对象信息
首先然后
配置完成后
配置完成后就可以做增删改查了。具体代码实现
import “classTableViewController.h”
import “ClassTableViewCell.h”
import “Entity.h”
import “AppDelegate.h”
@interface classTableViewController ()
@property(nonatomic, strong)NSManagedObjectContext *context;
@property(nonatomic, strong)NSMutableArray *datasource;
@end
@implementation classTableViewController
(NSMutableArray *)datasource{
if (!_datasource) {
self.datasource = [NSMutableArray array];
}
return _datasource;
}(void)viewDidLoad {
[super viewDidLoad];//获得当前被管理对象的上下文
self.context = ((AppDelegate *)[UIApplication sharedApplication].delegate).managedObjectContext;[self readData];
}
pragma mark 获取数据
(void)readData{
//读取文件
//1.创建一个FetchRequest抓取对象请求
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@”Entity”];//2.设置过滤条件
NSPredicate *pre = [NSPredicate predicateWithFormat:@”city=%@”,@”西安”];
request.predicate = pre;//3.设置排序
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@”city” ascending:YES];
request.sortDescriptors = @[sort];//4.执行请求
//创建一个数组接受返回值
NSArray *classes = [self.context executeFetchRequest:request error:nil];
[self.datasource setArray:classes];// NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// NSEntityDescription *entity = [NSEntityDescription entityForName:@”Entity” inManagedObjectContext:self.context];
// [fetchRequest setEntity:entity];
// // Specify criteria for filtering which objects to fetch
// NSPredicate *predicate = [NSPredicate predicateWithFormat:@”city =%@”, @”西安”];
// [fetchRequest setPredicate:predicate];
// // Specify how the fetched objects should be sorted
// NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@”city”
// ascending:YES];
// [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
//
// NSError *error = nil;
// NSArray *fetchedObjects = [self.context executeFetchRequest:fetchRequest error:&error];
// if (fetchedObjects == nil) {
return self.datasource;
// }
// [self.datasource setArray:fetchedObjects];
//
}
pragma mark 添加一个班级
(IBAction)addClass:(id)sender {
//1.创建一个班级对象//创建实体对象的描述 得到实体(表)是什么样的结构
NSEntityDescription *classED = [NSEntityDescription entityForName:@”Entity” inManagedObjectContext:self.context];//创建一个班级对象,这个对象继承与NSManagedObject,并且把这条数据保存到当前的上下文
Entity *class = [[Entity alloc]initWithEntity:classED insertIntoManagedObjectContext:self.context];//用UIImageJPEGRepresentation这个函数将图片转化成NSData
class.headImage = UIImageJPEGRepresentation([UIImage imageNamed:@”11.jpg”], 1.0);
int num = arc4random()%1000+1000;
class.name = [NSString stringWithFormat:@”XAS15%d”,num];
NSArray *cityArr = @[@”北京”,@”上海”,@”广州”,@”大连”,@”郑州”,@”西安”];
int index = arc4random()%6;
class.city = cityArr[index];
class.createTime = [NSDate date];//2.将此保存到文件
NSError *error;
if (!error) {
[self.context save:&error];
//3.添加到数据源
[self.datasource addObject:class];
//4.添加到UI界面
//生成最后一行的下标
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.datasource.count-1 inSection:0];
//将数据添加到列表的最后一行
[self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
//让tableView滑动到添加的那一条
[self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
pragma mark - Table view data source
(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return self.datasource.count;
}(UITableViewCell )tableView:(UITableView )tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
ClassTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@”CELL” forIndexPath:indexPath];// Configure the cell…
Entity *classModel = self.datasource[indexPath.row];
cell.headImage.image = [UIImage imageWithData:classModel.headImage];
cell.lable1.text = classModel.name;
cell.lable2.text = [classModel.createTime description];
cell.lable3.text = classModel.city;return cell;
}
pragma mark 修改数据
(void)tableView:(UITableView )tableView didSelectRowAtIndexPath:(NSIndexPath )indexPath{
//1.创建一个NSFetchRequest
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@”Entity”];
//2.设置过滤条件
NSPredicate *pre = [NSPredicate predicateWithFormat:@”city=%@”,@”大连”];
request.predicate = pre;
//3.设置排序
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@”city” ascending:YES];
request.sortDescriptors = @[sort];
//4.执行请求
NSArray *classes = [self.context executeFetchRequest:request error:nil];
//遍历查询返回数组
for (Entity *class in classes) {
//修改city为西安
class.city = @”西安”;
}
NSError *error;
[self.context save:&error];
[self.tableView reloadData];
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView )tableView canEditRowAtIndexPath:(NSIndexPath )indexPath {
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
//滑动删除
// Override to support editing the table view.
- (void)tableView:(UITableView )tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath )indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
//删除数据
//1.删除数据库里面的数据
Entity *class = self.datasource[indexPath.row];
[self.context deleteObject:class];
NSError *error;
if (!error) {
[self.context save:&error];//同步一下
//2.删除数据源里面的数据
[self.datasource removeObject:class];
//3.删除Ui界面的对应数据
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}