CoreData的学习

第一步:创建项目是勾选coredata,当然创建的时候没有勾选,之后还可以手动生产,

 

然后:创建数据库模型,及为其添加模型的属性。

 

 然后生成模型文件:

注意⚠️:首先设置为Manual/None  不然在编译的过程中也会自动生成模型文件 造成编译失败

模型文件生成后,不用做修改,

生成模型文件后,就可以使用了。

现在就开始上代码:

#import "ViewController.h"
#import "AppDelegate.h"
#import "Person+CoreDataClass.h"

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic, strong) NSMutableArray * dataSource;
@property (nonatomic, strong) AppDelegate * myAppdelegate;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    // 初始化数据源数组
    self.dataSource = [NSMutableArray array];
    
    self.tableView = [[UITableView alloc]initWithFrame:self.view.bounds];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    self.tableView.rowHeight = 50;
    
    UIButton *add = [UIButton buttonWithType:UIButtonTypeContactAdd];
    [add addTarget:self action:@selector(clickAdd) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightitem = [[UIBarButtonItem alloc]initWithCustomView:add];
    self.navigationItem.rightBarButtonItem = rightitem;
    
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    _myAppdelegate = delegate ;
    NSManagedObjectContext *context  = _myAppdelegate.persistentContainer.viewContext;
    
    // 进入控制器时 查询数据库数据
    /**
     两种方式创建request
     */
//    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
    NSFetchRequest *request = [Person fetchRequest];
    /**
     数据排序
     */
    NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];
    request.sortDescriptors = @[descriptor];
    /**
     刷选数据
     */
//    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age == 8"];
//    request.predicate = predicate;
    NSError *error = nil;
    NSArray *result = [context executeFetchRequest:request error:&error];
    for (Person * p in result) {
        NSLog(@"-查询结果:-----name:%@-------age:%lld",p.name,p.age);
    }
    [self.dataSource addObjectsFromArray:result];
    [self.tableView reloadData];
}

/**
 插入数据
 */
- (void)clickAdd
{
    NSManagedObjectContext *context  = _myAppdelegate.persistentContainer.viewContext;
    Person *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:context];
    person.name = @"jeck";
    NSInteger temp = random() % 10 + 1;
    person.age = temp;
    [self.dataSource addObject:person];
    [self.tableView reloadData];
    [_myAppdelegate saveContext];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    Person *modle = self.dataSource[indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"%@----%lld",modle.name,modle.age];
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

/**
 删除数据
 */
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        Person *p = self.dataSource[indexPath.row];
        [self.dataSource removeObject:p];
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
        [_myAppdelegate.persistentContainer.viewContext deleteObject:p];
        [_myAppdelegate saveContext];
    }
}

/**
 点击修改数据
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Person *p = self.dataSource[indexPath.row];
    p.name = @"rose";
    [_myAppdelegate saveContext];
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

 

简单说一下数据库的升级,模型版本的迁移:(能够使老版本的数据库正常使用)

 

新生成的新数据库文件:

 

切换之后,文件上勾选的是test_coreDate2了,此时就可以向新的模型库里添加新增的模型属性了,

然后需要生成一个模型的映射文件:

command + N

 

之后就会生成一个 v1.0_Tov1.1Model.xcmappingmodel 文件,前面的名字自己随意;

然后,就把旧的数据库的四个模型文件(Person+CoreDataClass.h  ...m   Person+CoreDataProperties.h ....m)删除,重新使用新的数据库test_CoreData2 创建模型文件。

看网上说的还需要修改Appdelegate中的代码,发现现在不用修改了。(想修改也找不到地方了,现在自动生成的代码和之前的不一样了)

 

在网上很多都是旧的,只发现这个比较新点 http://blog.csdn.net/willluckysmile/article/details/76464249 

posted @ 2018-01-10 22:32  新司机上路  阅读(169)  评论(0编辑  收藏  举报
本人qq1365102044,有问题欢迎沟通!