CoreData

作为一个IOS人士,这是第一次写自己的博客,

关于CoreData数据有下面的说法:

Core Data是一个功能强大的层,位于SQLite数据库之上,它避免了SQL的复杂性,能让我们以更自然的方式与数据库进行交互。

Core Data将数据库行转换为OC对象(托管对象)来实现,这样无需任何SQL知识就能操作他们。

Core Data位于MVC设计模式中的模型层,一般需要在设备上存储结构化数据时,考虑使用SQLite或是序列化等方法,而Core Data是这两种方法的混合体,并增加了一些功能,提供了SQL强大威力,但是用起来又和序列化一样简单。Core Data能将应用程序中的对象直接保存到数据库中,无需进行复杂的查询,也无需确保对象的属性名和数据库字段名对应,这一切都由Core Data完成。


Core Data的核心——托管对象

托管对象是要存储到数据库中的对象的一种表示,可以看成是SQL记录,它通常包含一些字段,这些字段与应用程序中要存储的对象的属性进行匹配,创建托管对象后,必须将气托管到托管对象上下文中,然后才可以存储到数据库中。

托管对象上下文:

托管对象上下文包含所有的托管对象,这些托管对象已经为提交给数据库准备就绪,在托管对象上下文中,可以添加、修改和删除托管对象,这一层相当于应用程序和数据库之间的缓冲区。

托管对象表:

托管对象表描述了数据库的架构(schema),供托管对象上下文与数据库交互时使用。托管对象表包含一些列实体描述,每个实体都描述了一个数据库表,用于将托管对象映射到数据库条目


#import "AppDelegate.h"

#import "Student.h"

@interface AppDelegate ()


@end


@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Override point for customization after application launch.

    //两种调用方式

//    [self saveContext];

//    [self.managedObjectContext save:nil];

    /*

    //路径

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

    //增删该查

    //

    //创建一个student对象;

   

    //1.1复杂方法创建对象

    //创建实体描述;

    NSEntityDescription * entityDescription = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:self.managedObjectContext];

    Student * student = [[Student alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:self.managedObjectContext];

    student.name = @"赛亚人";

    student.age = @18;

    student.gender = @"man";

    [self saveContext];

    */

   

    /*

    //创建对象,简单方法;

    Student * student2 = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:self.managedObjectContext];

    student2.name = @"悟空";

    student2.age = @19;

    student2.gender = @"man";

    [self saveContext];

   */

    

    /*

    //查询

    //设置检索条件

    //拼接检索条件,"and"连接,或者的话用"or"连接

    NSPredicate * predicate = [NSPredicate predicateWithFormat:@"name == %@ and age == %@ and gender == %@",@"赛亚人",@18,@"man"];

   NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName:@"Student"];

    request.predicate = predicate;

    NSError * error = nil;

    NSArray * array = [self.managedObjectContext executeFetchRequest:request error:&error];

    Student *tempStu = [array firstObject];

    NSLog(@"学生名:%@ ,年龄:%@ ,性别:%@",tempStu.name,tempStu.age,tempStu.gender);

    //无论是修改还是删除,都需要先查询才能操作;

    //

    tempStu.name = @"哈哈";

    tempStu.age = @20;

    tempStu.gender = @"g";

    [self.managedObjectContext save:nil];

   */

    //删除;

//    [self.managedObjectContext deleteObject:tempStu];

//    [self saveContext];


    return YES;

}

下面说以例子:

用 storyBoard创建一个导航控制器用来管理tableviewcontroller,点击上面的单元格push到下一个tableviewcontroller里

首先我们创建两个Model类 在XXX.xcdatamodeld文件里 一个类对应Teacher ,一个对应Student,一个老师对象可以有个学生.



在TeacherTableViewController里面在下一操作

#import "TeacherTableViewController.h"

#import "StudentTableViewController.h"

#import "Teacher.h"

#import "Student.h"

#import "AppDelegate.h"


@interface TeacherTableViewController ()

//数据源

@property (nonatomic,strong) NSMutableArray *teacherArray;

///数据管理器

@property (nonatomic,strong) NSManagedObjectContext *managedObjectContext;


@end


@implementation TeacherTableViewController


//添加按钮响应事件

- (IBAction)addTeacher:(UIBarButtonItem *)sender {

    //添加老师到数据源

    Teacher *teacher = [NSEntityDescription insertNewObjectForEntityForName:@"Teacher" inManagedObjectContext:self.managedObjectContext];


    teacher.name = [NSString stringWithFormat:@"胡歌%d",arc4random() %100];


    //老师的学生集合赋值

    for (int i = 0; i < 50; i++) {

        Student *student = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:self.managedObjectContext];


        student.name = [NSString stringWithFormat:@"花花%d",i];

        student.teachership = teacher;

    }

    //将当前创建的老师添加到数据源中

    [self.teacherArray addObject:teacher];

    //数据库中保存

    [self.managedObjectContext save:nil];

    //添加cell

    NSIndexPath *indexpath = [NSIndexPath indexPathForRow:self.teacherArray.count - 1 inSection:0];

    [self.tableView insertRowsAtIndexPaths:@[indexpath] withRowAnimation:UITableViewRowAnimationTop];


//    [self.tableView reloadData];


}


- (void)viewDidLoad {

    [super viewDidLoad];

    self.teacherArray = [NSMutableArray arrayWithCapacity:1];

    self.view.backgroundColor = [UIColor whiteColor];

    self.navigationItem.title = @"老师列表";

    //给数据管理器传值

    AppDelegate *appdelegate = [UIApplication sharedApplication].delegate;

    self.managedObjectContext = appdelegate.managedObjectContext;


    // 查询数据 teacher

    //检索条件

    NSFetchRequest *requst = [NSFetchRequest fetchRequestWithEntityName:@"Teacher"];


   NSArray *temArray = [self.managedObjectContext executeFetchRequest:requst error:nil];

    [self.teacherArray addObjectsFromArray:temArray];

//刷新操作

    [self.tableView reloadData];

}


- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


#pragma mark - Table view data source

//返回分区的个数

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {


    return 1;

}

//返回每一分区的行数

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {


    return self.teacherArray.count;

}


//返回单元格对象

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

    

    Teacher *teacher = self.teacherArray[indexPath.row];

    cell.textLabel.text = teacher.name;

    

    return cell;

}



/*

//系统默认的

// 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;

}

*/


// 提交编辑.

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle == UITableViewCellEditingStyleDelete) {

        //删除数据库中的数据

        Teacher *teacher = [self.teacherArray objectAtIndex:indexPath.row];

        NSMutableSet *set = [NSMutableSet setWithSet:teacher.studentship];

        for (Student *stu in set) {

            [self.managedObjectContext deleteObject:stu];

            [self.managedObjectContext save:nil];

        }


        [self.managedObjectContext deleteObject:teacher];

        [self.managedObjectContext save:nil];


        //删除数据源

        [self.teacherArray removeObjectAtIndex:indexPath.row];

        //修改界面

        [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

    }   

}

//桥之间的跳转传值

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {



    StudentTableViewController *studentVC = segue.destinationViewController;

    //传值

    studentVC.managedObjectContex = self.managedObjectContext;

    //获取到cell

    UITableViewCell *cell = sender;

    //根据cell 获取到indexPath

   NSIndexPath *indexpath = [self.tableView indexPathForCell:cell];

    //根据indexpath 获取到数组中的teacher

    Teacher *teacher = self.teacherArray[indexpath.row];

    studentVC.teacher = teacher;



}


学生管理器StudentTableViewController


#import <UIKit/UIKit.h>


@class Teacher;


@interface StudentTableViewController : UITableViewController

///学生的老师

@property  (nonatomic,strong) Teacher *teacher;

///数据管理器

@property (nonatomic,strong) NSManagedObjectContext *managedObjectContex;

@end



#import "StudentTableViewController.h"

#import "Student.h"


@interface StudentTableViewController ()

@property (nonatomic,strong) NSArray *studentArray;


@end


@implementation StudentTableViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    self.navigationItem.title = @"学生列表";

    //根据teacher获取到当前teacher管理下所有的学生

    //学生的查询

    //检索条件

    //指定查询那张表

    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Student"];

    //设置检索条件

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"teachership == %@",self.teacher];

    request.predicate = predicate;


  self.studentArray = [self.managedObjectContex executeFetchRequest:request error:nil];

    //刷新数据

    [self.tableView reloadData];


}


- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


#pragma mark - Table view data source


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {


    return 1;

}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {



    return self.studentArray.count;

}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"stu" forIndexPath:indexPath];

    

    Student *stu = self.studentArray[indexPath.row];

    cell.textLabel.text = stu.name;

    

    return cell;

}

//提交编译操作

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle == UITableViewCellEditingStyleDelete) {

        //从数据库中删除

        //先获取到学生的信息

        Student *student = [self.studentArray objectAtIndex:indexPath.row];

        //根据获取到的学生信息从数据库找到学生对象并删除

        [self.managedObjectContent deleteObject:student];

        //保存操作

        [self.managedObjectContent save:nil];

        //从数据源中删除 删除数据

        [self.studentArray removeObjectAtIndex:indexPath.row];


        [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

    }   

}











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值