CoreData单表

这里写图片描述

点击下列选项生成文件
这里写图片描述

一、创建继承于 NSObject 的类来定义方法
例:类名为:DataBase

DataBase.h

#import "Entity+CoreDataClass.h"   // 导入实体的头文件
#import "AppDelegate.h" // 调用容器
// 定义方法
// 单例方法
+(instancetype)initData;

// 添加数据
-(void)addData:(NSDictionary *)dic;

// 删除数据
-(void)deleteData:(Entity *)data;

// 修改数据
-(void)changeData;

// 查询数据
-(NSMutableArray *)showArr;

DataBase.m

// 创建单例变量
static DataBase *dataBase = nil;
// 实现方法
// 单例方法
+(instancetype)initData
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        dataBase = [[DataBase alloc] init];
    });
    return dataBase;
}
+(instancetype)allocWithZone:(struct _NSZone *)zone
{
    if (!dataBase) {

        dataBase = [super allocWithZone:zone];
    }
    return dataBase;
}
-(id)copy
{
    return self;
}
-(id)mutableCopy
{
    return self;
}

// 添加数据
-(void)addData:(NSDictionary *)dic
{
    AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate];

    // 创建实体
    Entity *entity = [NSEntityDescription insertNewObjectForEntityForName:@"Entity" inManagedObjectContext:app.persistentContainer.viewContext];

    entity.name = [dic objectForKey:@"name"];
    entity.age = dic [@"age"];

    [app saveContext];

}

// 删除数据
-(void)deleteData:(Entity *)data
{
    AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate];

    [app.persistentContainer.viewContext deleteObject:data];

    // 调用保存方法
    [app saveContext];
}

// 修改数据
-(void)changeData
{
    // 调用容器
    AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate];

    [app saveContext];
}

// 查询数据
-(NSMutableArray *)showArr
{
    // 创建对象 调用容器
    AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate];

    // 抓取数据
    NSFetchRequest *request = [[NSFetchRequest alloc] init];

    // 从实体描述对象中抓取
    NSEntityDescription *enti = [NSEntityDescription entityForName:@"Entity" inManagedObjectContext:app.persistentContainer.viewContext];

    // 向实体抓取
    [request setEntity:enti];

    // 数组
    NSArray *array = [app.persistentContainer.viewContext executeFetchRequest:request error:nil];

    // 返回 array 报黄,进行深复制[array mutableCopy]
    return [array mutableCopy];

}

二 、创建一个继承于 UIView 的类构造视图界面
例:类名为:MyView
MyView.h
根据属性的个数创建对应的布局

// 定义属性
@property (nonatomic ,strong) UITextField *nameTf, *ageTf;
// 重写初始化方法
-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {

        [self addSubview:self.nameTf];
        [self addSubview:self.ageTf];
    }
    return self;
}

// 懒加载
// 名字
-(UITextField *)nameTf
{
    if (!_nameTf) {

        _nameTf = [[UITextField alloc] initWithFrame:CGRectMake(0, 90, self.frame.size.width, 50)];
        _nameTf.borderStyle = UITextBorderStyleRoundedRect;
        _nameTf.placeholder = @"yly";
        _nameTf.textAlignment = NSTextAlignmentCenter;
    }
    return _nameTf;
}
// 年龄
-(UITextField *)ageTf
{
    if (!_ageTf) {

        _ageTf = [[UITextField alloc] initWithFrame:CGRectMake(0, 150, self.frame.size.width, 50)];
        _ageTf.borderStyle = UITextBorderStyleRoundedRect;
        _ageTf.placeholder = @"yly";
        _ageTf.textAlignment = NSTextAlignmentCenter;
    }
    return _ageTf;
}

三、 1、创建继承于 UITableViewController 的类 – 例:类名为 MainTableViewController
2、创建继承于UIViewController的类 – 例 :类名为 SecViewController
1)、在MainTableViewController.m中
导入头文件

#import "SecViewController.h"   // 展示视图
#import "Entity+CoreDataClass.h"    // 实体
#import "DataBase.h"    // 数据
// 创建可变数组
{
    NSMutableArray *array;
}
- (void)viewDidLoad {
    [super viewDidLoad];

    // 标题
    self.title = @"CoreData数据库";

    // 表格行高
    self.tableView.rowHeight = 80;

    // 初始化数组
    array = [NSMutableArray array];

    // 跳转按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"跳转" style:UIBarButtonItemStylePlain target:self action:@selector(tiaozhuan)];

}
// 实现跳转按钮点击事件
-(void)tiaozhuan
{
    // 创建下一个页面的主页面
    SecViewController *secVC = [[SecViewController alloc] init];

    // 执行跳转 -- 左右侧滑
    [self.navigationController pushViewController:secVC animated:YES];
}

// 视图将要显示
-(void)viewWillAppear:(BOOL)animated
{
    // 调用数据库查询方法
    array = [[DataBase initData] showArr];

    // 刷新表格
    [self.tableView reloadData];
}
#pragma mark -
#pragma mark UITableViewDataSource
// 行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return array.count;
}
// 单元格
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 查找 cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@""];
    // 如果找不到就创建 cell
    if (cell == nil) {

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];
    }

    // 初始化对象
    Entity *en = array[indexPath.row];

    // 设置内容
    cell.textLabel.text = [NSString stringWithFormat:@"姓名:%@\n年龄:%@",en.name, en.age];

    // 自动换行
    cell.textLabel.numberOfLines = 0;

    // 返回 cell
    return cell;

}
// 点击表格跳转
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 创建下一面的主页面
    SecViewController *secV = [[SecViewController alloc] init];

    // 属性传值
    secV.entity = array[indexPath.row];

    // 跳转
    [self.navigationController pushViewController:secV animated:YES];
}

// 删除行
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    Entity *delEntity = array[indexPath.row];

    [[DataBase initData] deleteData:delEntity];

    // 调用查询方法
    array = [[DataBase initData] showArr];

    // 刷新表格
    [self.tableView reloadData];
}

【属性传值的地方会报错,是因为属性还没有定义,写完下面的SecViewController.h中定义的属性后就不会报错了】

2)、SecViewController.h
导入头文件

#import "Entity+CoreDataClass.h"  // 实体表的头文件
// 定义属性
@property (nonatomic ,strong) Entity *entity;

3)、SecViewController.m
导入头文件

#import "Entity+CoreDataClass.h"
#import "DataBase.h"    // 处理数据
#import "MyView.h"  // 视图
// 定义视图类的成员变量
{
    MyView *myView;
}
- (void)viewDidLoad {
    [super viewDidLoad];

    // 初始化视图
    myView = [[MyView alloc] initWithFrame:self.view.frame];
    myView.backgroundColor = [UIColor magentaColor];
    self.view = myView;

    // 传值
    myView.nameTf.text = self.entity.name;
    myView.ageTf.text = self.entity.age;

    // 判断添加标题
//    if (myView.nameTf.text.length <= 0) {
    if (!self.entity) {

        self.title = @"添加数据";
        // 创建添加按钮
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"添加" style:UIBarButtonItemStylePlain target:self action:@selector(didClickAdd)];

    }else{

        self.title = @"修改数据";
        // 创建修改按钮
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"修改" style:UIBarButtonItemStylePlain target:self action:@selector(didClickSave)];

    }
}
// 实现 添加按钮点击事件
-(void)didClickAdd
{
    // key 值和 value 值要相对应
    NSDictionary *dic = @{@"name":myView.nameTf.text, @"age":myView.ageTf.text};

    // 调用添加数据的方法
    [[DataBase initData] addData:dic];

    // 跳转回上一视图
    [self.navigationController popViewControllerAnimated:YES];
}

//  实现 修改按钮点击事件
-(void)didClickSave
{
    self.entity.name = myView.nameTf.text;
    self.entity.age = myView.ageTf.text;

    // 调用修改数据方法
    [[DataBase initData] changeData];

    // 跳转回上一视图
    [self.navigationController popViewControllerAnimated:YES];

}

AppDelegate.h中更改主窗口
导入头文件

#import "MainTableViewController.h"
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:[[MainTableViewController alloc] init]];

    return YES;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值