• iOS:CoreData数据库的使用三(数据库和tableView表格一起使用)


    CoreData数据库是用来持久性存储数据的,那么,我们再从该数据库中取出数据干什么呢?明显的是为了对数据做操作,这个过程中可以将它们直观的显示出来,即通过表格的形式显示出来。CoreData配合tableView一起使用,是很常用的一种方式,直观、清晰明了。

    下面就来具体的举个例子:

    要求:将数据库中的数据显示在表格中,并且可以进行删除、插入等一些操作。

    前期的具体步骤:

    1、创建项目时,勾选Use Core Data,生成CoreData_____.xcdatamodel文件;

    2、点击CoreData_____.xcdatamodel文件,进入项目面板,点击左下角的Add Entity创建实体对象;

        

    3、在Attributes处点击'+'号,添加实体对象的属性

    4、选中实体对象,点击模拟器菜单栏上的Editor下的create NSManagedObjectSubclass..,自动创建该实体对象的类

            

    5、点击项目面板右下角的style查看所创建的表

    6、在故事板Storyboard中拖入一个表格UITableView,并将tableView和控制类进行IBOutlet关联

    好了,在AppDelegate和Student类编译器自动帮助声明和定义了需要的方法和属性,前期的工作已经完成,最后就是代码来操作数据库了:

    在AppDelegate类中准备测试数据并将它们存储到数据库中:

     1 #import "AppDelegate.h"
     2 #import "Student.h"
     3 
     4 @interface AppDelegate ()
     5 @property (assign,nonatomic)BOOL isInserted;
     6 @end
     7 
     8 @implementation AppDelegate
     9 
    10 //准备测试数据
    11 -(void)addStudentWithName:(NSString *)name andAge:(NSNumber*)age andGender:(NSNumber*)gender
    12 {
    13     //取数据库中实体对象
    14     Student *student = [NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass([Student class]) inManagedObjectContext:self.managedObjectContext];
    15     
    16     student.name = name;
    17     student.age = age;
    18     student.gender = gender;
    19 }
    20 
    21 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    22     
    23     //在偏好设置中设置标识符,用来防止数据被重复插入
    24     NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    25     self.isInserted = [userDefaults boolForKey:@"isInserted"];
    26     
    27     //设置实体对象的属性
    28     if(!self.isInserted)
    29     {
    30         [self addStudentWithName:@"张三" andAge:@20 andGender:@'M'];
    31         [self addStudentWithName:@"李四" andAge:@21 andGender:@'F'];
    32         [self addStudentWithName:@"王五" andAge:@20 andGender:@'M'];
    33         [self addStudentWithName:@"赵六" andAge:@23 andGender:@'F'];
    34         [self addStudentWithName:@"陈七" andAge:@24 andGender:@'F'];
    35         [self addStudentWithName:@"郑八" andAge:@25 andGender:@'M'];
    36         [self addStudentWithName:@"戴九" andAge:@19 andGender:@'M'];
    37         [self addStudentWithName:@"刘十" andAge:@22 andGender:@'F'];
    38     }
    39     
    40     //设置偏好设置,并强制写到文件中
    41     [userDefaults setBool:YES forKey:@"isInserted"];
    42     [userDefaults synchronize];
    43     
    44     //保存数据到持久层
    45     [self saveContext];
    46     
    47     return YES;
    48 }

    在控制器类ViewController中取出数据库中的数据,并将它们显示在表格中,然后进行删除和插入操作:

      1 #import "ViewController.h"
      2 #import "AppDelegate.h"
      3 #import "Student.h"
      4 
      5 @interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
      6 @property (weak, nonatomic) IBOutlet UITableView *tableView;
      7 @property (strong,nonatomic)NSMutableArray *stus;
      8 @end
      9 
     10 @implementation ViewController
     11 
     12 - (void)viewDidLoad {
     13     [super viewDidLoad];
     14     //设置应用程序代理
     15     AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
     16     
     17     //设置数据源和代理
     18     self.tableView.dataSource = self;
     19     self.tableView.delegate = self;
     20     
     21     //从CoreData数据库中取出实体对象信息
     22     
     23     //创建请求对象
     24     NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:NSStringFromClass([Student class])];
     25     
     26     //批处理
     27     fetchRequest.fetchBatchSize = 10;
     28     
     29     //创建排序对象
     30     NSSortDescriptor *ageSort = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];
     31     [fetchRequest setSortDescriptors:@[ageSort]];
     32     
     33     //上下文发送查询请求
     34     NSError *error = nil;
     35     NSArray *array = [appDelegate.managedObjectContext executeFetchRequest:fetchRequest error:&error];
     36     if(error)
     37     {
     38         return; //获取数据失败
     39     }
     40     
     41     self.stus = [NSMutableArray arrayWithArray:array];
     42     
     43 }
     44 
     45 //设置行
     46 -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
     47 {
     48     return self.stus.count;
     49 }
     50 //设置每一个单元格的内容
     51 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
     52 {
     53     //1.根据reuseIdentifier,先到对象池中去找重用的单元格对象
     54     static NSString *reuseIdentifier = @"stuCell";
     55     UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
     56     //2.如果没有找到,自己创建单元格对象
     57     if(cell == nil)
     58     {
     59         cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier];
     60     }
     61     //3.设置单元格对象的内容
     62     Student *student = [self.stus objectAtIndex:indexPath.row];
     63     cell.textLabel.text = student.name;
     64     cell.detailTextLabel.text = [NSString stringWithFormat:@"%@  %c",student.age,(char)[student.gender integerValue]];
     65     return cell;
     66 }
     67 
     68 //编辑单元格
     69 -(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
     70 {
     71     return YES;
     72 }
     73 
     74 //编辑类型
     75 -(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
     76 {
     77     //删除
     78     return UITableViewCellEditingStyleDelete;
     79 }
     80 
     81 //对编辑类型的处理
     82 -(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
     83 {
     84     
     85     AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
     86     
     87     //删除CoreData数据库中数据
     88     Student *student = [self.stus objectAtIndex:indexPath.row];
     89     [appDelegate.managedObjectContext deleteObject:student];
     90     NSError *error = nil;
     91     [appDelegate.managedObjectContext save:&error];
     92     if(error)
     93     {
     94           NSLog(@"删除失败");
     95     }
     96     
     97     //删除数据源数据
     98     [self.stus removeObjectAtIndex:indexPath.row];
     99 
    100     
    101     //删除一条记录的同时,往CoreData数据库插入两条数据
    102     [appDelegate addStudentWithName:@"小明" andAge:@24 andGender:@'M'];
    103     [appDelegate addStudentWithName:@"小李" andAge:@25 andGender:@'M'];
    104     
    105     [appDelegate.managedObjectContext save:&error];
    106     if(error)
    107     {
    108         NSLog(@"删除失败");
    109     }
    110

            //局部刷新表格

              //[self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];

    111     
    112     //整体刷新表格
    113     [self.tableView reloadData];
    114 }
    115 
    116 @end

     演示结果如下:

    从数据库取出数据显示在表格上                         在单元格上从左向右滑动删除数据

              

    删除几个数据后显示结果                 删除一次时,(重新取数据仅仅删除了郑八时)同时插入两个指定的数据后结果

              

  • 相关阅读:
    2021-6-3 日报博客
    2021-6-2 日报博客
    2021-6-1 日报博客
    2021-5-31 日报博客
    团队博客——十日冲刺结束
    团队博客——十日冲刺9
    团队博客——十日冲刺8
    团队博客——十日冲刺7
    周总结9
    团队博客——十日冲刺6
  • 原文地址:https://www.cnblogs.com/XYQ-208910/p/4830623.html
Copyright © 2020-2023  润新知