CoreData数据持久化实现收藏功能
主要实现的功能 :底部有两个标签控制器 点击第一个标签控制器的单元格 第二个控制器里就有相应的数据 实现数据持久化收藏功能
第一步:首先创建两个标签控制器
#import “oneViewController.h”
#import “ViewController.h”
#import “twoViewController.h”
@interface oneViewController ()
@end
@implementation oneViewController
-
(void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.ViewController *one=[ViewController new];
UINavigationController *onenav=[[UINavigationController alloc]initWithRootViewController:one];
onenav.tabBarItem=[[UITabBarItem alloc]initWithTitle:@“首页” image:[UIImage imageNamed:@“5”] selectedImage:[UIImage imageNamed:@“5”]];
twoViewController *two=[twoViewController new];
UINavigationController *twonav=[[UINavigationController alloc]initWithRootViewController:two];
twonav.tabBarItem=[[UITabBarItem alloc]initWithTitle:@“我的收藏” image:[UIImage imageNamed:@“5”] selectedImage:[UIImage imageNamed:@“5”]];
[email protected][onenav,twonav];
}
@end
因为当时没有在VC里面创建标签控制器 在OneVc创建的标签栏 所以在Appdelegate.m里面 设置根控制器为OneVc
#import “AppDelegate.h”
#import “oneViewController.h”
@interface AppDelegate ()
@end
@implementation AppDelegate
-
(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
self.window.rootViewController=[oneViewController new];return YES;
}
第二部:开始解析接口里面的数据 并且进行CoreData实现收藏功能
1.创建DataModel继承NSObject 在DataModel.h里面定义接口里面的属性
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface DataModel : NSObject
@property(nonatomic,strong)NSString *content;
@property(nonatomic,strong)NSString *updatetime;
@property(nonatomic,strong)NSString *hashId;
@end
然后在DataModel.m里面 写-(void)setValue:(id)value forUndefinedKey:(NSString *)key{
}这个方法
--------- 其次在创建一个Model类继承NSobject 在这个Model类里面主要写 了一些关于CoreData的一些增删改查的一些数据
首先在Model.h里定义一些方法:
#import <Foundation/Foundation.h>
#import “AppDelegate.h”
#import “Entity+CoreDataClass.h”
NS_ASSUME_NONNULL_BEGIN
@interface Model : NSObject{
AppDelegate *app;
}
//创建单利方法
//单利方法
+(instancetype)initData;
//添加数据
-(void)addData:(NSDictionary * )dic;
//删除数据
-(void)deleteData:(Entity *)data;
//修改
-(void)upData;
//查询
-(NSMutableArray *)array;
@end
其次在Model.m里面 实现这些方法
#import “Model.h”
#import “DataModel.h”
//创建静态变量
static Model *da;
@implementation Model
+(instancetype)initData{
if (!da) {
da = [[Model alloc] init];
}
return da;
}
-(void)addData:(NSDictionary *)dic{
//创建appdelegate对象
app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//创建实体对象 NSEntityDescription(实体描叙对象)
Entity *cla = [NSEntityDescription insertNewObjectForEntityForName:@"Entity" inManagedObjectContext:app.persistentContainer.viewContext];
// DataModel *mod=[DataModel new];
// cla.name=dic[mod.content];
// cla.time=dic[mod.updatetime];
NSLog(@"dic====%@",[dic objectForKey:@"name"]);
NSLog(@"time====%@",[dic objectForKey:@"time"]);
cla.name=dic[@"name"];
cla.time=dic[@"time"];
//
[app saveContext];
}
//删除数据
-
(void)deleteData:(Entity *)data{
//创建appdelegate对象
app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//删除
[app.persistentContainer.viewContext deleteObject:data];
//保存数据
[app saveContext];
}
//修改数据
-
(void)upData{
//创建appdelegate对象
app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//保存数据
[app saveContext];
}
//查询数据
-
(NSMutableArray *)array{
//创建appdelegate对象
app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//创建请求数据对象
NSFetchRequest *requst = [[NSFetchRequest alloc] init];
//创建实体描述类
NSEntityDescription *ent = [NSEntityDescription entityForName:@“Entity” inManagedObjectContext:app.persistentContainer.viewContext];
//获取数据
[requst setEntity:ent];
//从实体中获取数据
NSArray *arr = [app.persistentContainer.viewContext executeFetchRequest:requst error:nil];return [arr mutableCopy];
}
@end
2.然后在View文件夹里面创建TableViewCell 继承UITableViewCell
利用xib进行约束
进行拖拽 在TableViewCell.h里面 引入DataModel的头文件
#import <UIKit/UIKit.h>
#import “DataModel.h”
NS_ASSUME_NONNULL_BEGIN
@interface TableViewCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel *lab1;
@property (weak, nonatomic) IBOutlet UILabel *lab2;
-(void)setDataModel:(DataModel *)model;
@end
在TableViewCell.m里面 :-(void)setDataModel:(DataModel *)model{
if (model) {
self.lab1.text=model.content;
self.lab2.text=model.updatetime;
}
}这个方法
3.在VC.m里面进行解析接口的数据 并且点击单元格 进行添加数据
#import “ViewController.h”
#import <AFNetworking.h>
#import “TableViewCell.h”
#import “DataModel.h”
#import “Model.h”
#import “twoViewController.h”
@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView *tab;
@property(nonatomic,strong)NSMutableArray *arr;
@end
@implementation ViewController
-
(void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.tab=[[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
[email protected]“好好学习”;
self.tab.delegate=self;
self.tab.dataSource=self;
self.arr=[[NSMutableArray alloc]init];[self.view addSubview:self.tab];
[self.tab registerNib:[UINib nibWithNibName:@“TableViewCell” bundle:nil] forCellReuseIdentifier:@“cell”];
[self loadData];
}
-(void)loadData{
AFHTTPSessionManager *manger=[AFHTTPSessionManager manager];
manger.responseSerializer=[AFHTTPResponseSerializer serializer];
[manger GET:@"http://v.juhe.cn/joke/content/list.php?key=eaaf69cdca2f46e403a264f5ef7cb74b&time=1418816972" parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"请求成功");
NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:1 error:nil];
NSDictionary *dic1=[dic objectForKey:@"result"];
NSDictionary *arr=[dic1 objectForKey:@"data"];
NSLog(@" 随意%@",arr);
for (NSDictionary *dic in arr) {
DataModel *model=[DataModel new];
[model setValuesForKeysWithDictionary:dic];
[self.arr addObject:model];
NSLog(@"%@",self.arr);
}
dispatch_async(dispatch_get_main_queue(), ^{
[self.tab reloadData];
});
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"请求失败");
}];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.arr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *[email protected]"cell";
TableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:oj];
if (cell==nil) {
cell=[[TableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:oj];
}
DataModel *model=self.arr[indexPath.row];
cell.lab1.text=model.content;
cell.lab2.text=model.updatetime;
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[[Model initData]addData:@{@"name":[self.arr[indexPath.row] content],@"time":[self.arr[indexPath.row] updatetime]}];
[self.tab deselectRowAtIndexPath:indexPath animated:YES];
}
@end
4.其次创建第二个控制器twoViewController
在two.m里面实现视图即将出现的时候讲数据添加到表格中并且删除数据
#import “twoViewController.h”
#import “Model.h”
#import “DataModel.h”
#import “Entity+CoreDataClass.h”
@interface twoViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView *tab;
@property(nonatomic,strong)NSMutableArray *array;
@end
@implementation twoViewController
-
(void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.self.tab=[[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
self.tab.delegate=self;
self.tab.dataSource=self;[self.view addSubview:self.tab];
self.array=[[NSMutableArray alloc]init];
// [self dian];
}
//视图即将出现
-(void)viewWillAppear:(BOOL)animated{
self.array=[[Model initData]array];
[self.tab reloadData];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.array.count;
}
-(void)dian{
DataModel *mode=[DataModel new];
NSDictionary *[email protected]{@"name":mode.content,@"time":mode.updatetime};
[[Model initData]addData:dic];
[self.navigationController popViewControllerAnimated:YES];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *[email protected]"cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:oj];
if (cell==nil) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:oj];
}
self.tab.rowHeight=200;
// DataModel *mod=_array[indexPath.row];
//将数据放到实体对象里面通过实体对象进行赋值
Entity *cla=_array[indexPath.row];
// DataModel *model=self.array[indexPath.row];
cell.textLabel.text=cla.name;
cell.textLabel.numberOfLines=0;
cell.detailTextLabel.text=cla.time;
return cell;
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
//创建实体
Entity *cla=self.array[indexPath.row];
//调用删除数据的方法
[[Model initData]deleteData:cla];
//重新获取数据
self.array=[[Model initData]array];
//刷新表格
[self.tab reloadData];
}
@end