[iOS]30分钟入门OC-CoreData框架

一:什么是CoreData?

CoreData是苹果公司封装的进行数据持久化的框架,首次在IOS3.0版本的系统中出现,它允许按照实体–属性–值的模型组织数据,并以XML,二进制文件或者SQLite数据文件的格式持久化数据
(1)CoreData不是数据库,它只是操作数据库的框架
(2)CoreData不仅仅可以对数据库进行操作,而且还可以对xml和二进制文件进行操作
(3)可以节省代码量,一般要节省30%到70%的代码量

二:效果展示

《[iOS]30分钟入门OC-CoreData框架》

三:基本配置

(1)勾选”Use Core Data

《[iOS]30分钟入门OC-CoreData框架》

四:布局配置

(1)去掉”Use Auto Layout“和”Use Size Classes

《[iOS]30分钟入门OC-CoreData框架》

(2)可视化添加顶部导航栏

在”Editor“–>”Embed In“–>选择”Navigation Controller“即可在模型上直接添加

《[iOS]30分钟入门OC-CoreData框架》

(3)在组件中搜索”bar“找到item,拖拽到Navigation上面,并且可以对其进行自定义.

《[iOS]30分钟入门OC-CoreData框架》
《[iOS]30分钟入门OC-CoreData框架》

样式,样色,位置全部都可以进行自定义

《[iOS]30分钟入门OC-CoreData框架》

(4)添加TableView,找到灰色的”TableView“,将其拖拽到ViewController的正中间的位置,其大小可以进行拖拽来进行控制

《[iOS]30分钟入门OC-CoreData框架》

(5)选择”Table View“,点击最右键,将”dataSource“和”delegate“对”View Controller“进行关联

《[iOS]30分钟入门OC-CoreData框架》

(6)点击”Table View“中的”Prototype Cells“属性,其表示的其实是显示的列数

《[iOS]30分钟入门OC-CoreData框架》

表现为展示的一列

《[iOS]30分钟入门OC-CoreData框架》

五:数据库操作

(1)数据库添加实体对象:点击”SQLiteTest.xcdatamodeld

《[iOS]30分钟入门OC-CoreData框架》

(2)添加实体对象”Clothes“,其实这个实体对象相当于数据库中的表

《[iOS]30分钟入门OC-CoreData框架》

《[iOS]30分钟入门OC-CoreData框架》

在该对象(表)中,添加属性

《[iOS]30分钟入门OC-CoreData框架》

点击”
Editor“–>”
Create NSManagedObject Subclass“–>将会生成关于”
Clohes“的实现

《[iOS]30分钟入门OC-CoreData框架》

–>

《[iOS]30分钟入门OC-CoreData框架》

这个地方需要注意,如果在原来的Entity进行重命名,生成的数据库表名仍然为原来的值,唯一的办法是删掉重新写

此外,在”
AppDelegate.h“中还会
自动生成三个对象和两个方法

//
//  AppDelegate.h
//  SQLiteTest
//
//  Created by AqiuBeats on 16/10/10.
//  Copyright © 2016年 AqiuBeats. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
/**
 *  被管理对象上下文(数据管理器),相当于一个临时数据库(可视化建模的文件)
 */
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
/**
 *  被管理对象模型(数据模型器)
 */
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
/**
 *  持久化储存助理(数据链接器),整个CoreData框架的核心
 */
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
/**
 *  把我们临时数据库中进行的改变进行永久保存
 */
- (void)saveContext;
/**
 *  获取真实文件的储存路径
 */
- (NSURL *)applicationDocumentsDirectory;


@end

(3)对TableView中的”Cell“进行设置

在对行数设置为1之后

《[iOS]30分钟入门OC-CoreData框架》

《[iOS]30分钟入门OC-CoreData框架》

将该
cell的样式设置为
basic

《[iOS]30分钟入门OC-CoreData框架》

(4)主体代码

//
//  ViewController.m
//  SQLiteTest
//
//  Created by AqiuBeats on 16/10/10.
//  Copyright © 2016年 AqiuBeats. All rights reserved.
//

#import "ViewController.h"
#import "AppDelegate.h"
#import "Clothes+CoreDataProperties.h"
#import "Clothes.h"

/**
 *  设置"UITableViewDelegate"和"UITableViewDataSource"可以获取TableView的使用方法
 */
@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>
- (IBAction)addModel:(id)sender;
@property (weak, nonatomic) IBOutlet UITableView *tableview;

@property(nonatomic,strong)NSMutableArray* dataSource;

//声明一个AppDelegate对象属性,来调用类中属性,比如被管理对象个上下文
@property(nonatomic,strong)AppDelegate* myAppDelegate;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化数组
    self.dataSource=[NSMutableArray array];
    //初始化AppDelegate
    self.myAppDelegate=[UIApplication sharedApplication].delegate;
    //对TableView加上注册方法,"cell"表示的是自定义的方法
    [self.tableview registerClass :[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    
#warning 查--查询数据
    //1.NSFetchRequest对象
    NSFetchRequest* request=[[NSFetchRequest alloc]initWithEntityName:@"Clothes"];
    //2.设置排序
//    //2.1创建排序描述对象(以int类型的价格为例,进行升序排列)
//    NSSortDescriptor *sortFunc=[[NSSortDescriptor alloc]initWithKey:@"price" ascending:YES];
//    request.sortDescriptors=@[sortFunc];
    //3.执行这个查询请求
    NSError* error=nil;
    NSArray *arr=[self.myAppDelegate.managedObjectContext executeFetchRequest:request error:&error];
    //给数据源数组中添加数据
    [self.dataSource addObjectsFromArray:arr];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//tableView的delegate和dataSource的方法
/**
 *  返回分区中的行数,相当于listview的item数目
 */
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}
/**
 *  返回分区的个数
 */
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
/**
 *  对每个cell进行构造,相当于listview的item
 */
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell* cell=[tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    Clothes* cloth=self.dataSource[indexPath.row];
    cell.textLabel.text=[NSString stringWithFormat:@"品牌:%@--价格:%@",cloth.brand,cloth.price];
    return cell;
}
//允许tableView可编辑,这样就可以手动进行编辑了
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}
//对tableview的item可以进行各种手势操作
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    //滑动删除样式
    if (editingStyle==UITableViewCellEditingStyleDelete) {
#warning 删--删除数据,并对视图进行实时更新
        //删除数据源
        Clothes *cloth=self.dataSource[indexPath.row];
        [self.dataSource removeObject:cloth];
        //删除数据管理中的数据
        [self.myAppDelegate.managedObjectContext deleteObject:cloth];
        //将删除的更改进行永久保存
        [self.myAppDelegate saveContext];
        //删除单元格
        [self.tableview deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        
    }
}
#warning 改--更改数据的属性值,并对视图进行实时更新
//点击cell来修改数据
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"当前位置%ld",(long)indexPath.row);
    //1.先找到模型对象
    Clothes* cloth=self.dataSource[indexPath.row];
    //2.将该熟悉值更改
    cloth.brand=@"Adidas";
    //3.刷新视图
    [self.tableview reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    //4.对数据的更改进行永久的保存
    [self.myAppDelegate saveContext];
}

/**
 *  插入数据
 */
- (IBAction)addModel:(id)sender {
#warning 增--插入数据
    //创建实体描述
    NSEntityDescription* description=[NSEntityDescription entityForName:@"Clothes" inManagedObjectContext:self.myAppDelegate.managedObjectContext];
    //1.先创建一个模型对象
    Clothes* cloth=[[Clothes alloc]initWithEntity:description insertIntoManagedObjectContext:self.myAppDelegate.managedObjectContext];
    //2.对Clothe的对象属性进行赋值
    cloth.brand=@"Puma";
    int priceCC=arc4random()%1000+1;
    cloth.price=[NSNumber numberWithInt:priceCC];
    //插入数据源数组(数组是可以存储实体对象的)
    [self.dataSource addObject:cloth];
    //插入UI
    [self.tableview insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.dataSource.count-1 inSection:0]] withRowAnimation:UITableViewRowAnimationLeft];
    //对数据管理器中的更改进行永久存储
    [self.myAppDelegate saveContext];
    NSLog(@"%@",NSHomeDirectory());

}

@end

六:可视化SQLite文件

(1)所需要的工具:FireFox浏览器的插件

《[iOS]30分钟入门OC-CoreData框架》

(2)获取数据库文件

 NSLog(@"%@",NSHomeDirectory())

来获取document文件夹地址
注意:要想获得完整的数据库表的数据,以下三个文件一个都不能少!!!@@!

《[iOS]30分钟入门OC-CoreData框架》

(3)使用火狐插件打开该SQLite文件,通过该文件的形式可以证明我的猜想,生成的实体类即为一张表

该表命名的规则”Z”+”Clothes”(大写转化)

《[iOS]30分钟入门OC-CoreData框架》

可以可视化预览表中内容,其数据库字段写法为”Z”+”price”(大写转化)和”Z”+”brand”(大写转化)

《[iOS]30分钟入门OC-CoreData框架》

源码地址:https://github.com/AqiuBeats/SQLiteTest

完毕!

    原文作者:AqiuBeats
    原文地址: https://www.jianshu.com/p/0c707c25b6ca
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞