iOS Xcode8下CoreData的简单应用

原来没怎么使用过CoreData,最近心血来潮使用了一下,简直是很好用啊。。。相比于之前的Xcode版本,Xcode8下的CoreData又简单了不少。。。

预备工作

1.新建一个工程:
这里写图片描述
这里不要忘记打上勾哦!

2.然后就会发现工程里多出来一个这样的文件:
这里写图片描述

3.然后这样搞一下:
应该很清楚吧

在之前的Xcode版本里,这时候应该选择Xcode工具栏中的Editor->Create NSManagedObject Subclass…,从而产生实体相对应的类,但是在Xcode8中,不用了!有没有很开心???如果你又多操作了这一步,会报错的,亲身爬坑体会。

具体操作

1.添加数据

NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.appdelegate.persistentContainer.viewContext];
    Person *person = [[Person alloc]initWithEntity:entityDescription insertIntoManagedObjectContext:self.appdelegate.persistentContainer.viewContext];

    person.name = [NSString stringWithFormat:@"JACK%d",arc4random()%100];
    person.age = arc4random()%60+1;
    person.sex = arc4random()%2==0?@"man":@"woman";

    [self.dataArray insertObject:person atIndex:0];

    [self.appdelegate saveContext];

    [self.tableView reloadData];

只写这些东西会crash的,需要在viewdidload中,将coreData中的数据添加到数据源中:

self.appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.appdelegate.persistentContainer.viewContext];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    //    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age = 21", ];
    //    [fetchRequest setPredicate:predicate];
    // Specify how the fetched objects should be sorted
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];

    NSError *error = nil;
    NSArray *fetchedObjects = [self.appdelegate.persistentContainer.viewContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"数据查询错误%@",error);
    }else{
        //将查询到的数据添加到数据源中
        [self.dataArray addObjectsFromArray:fetchedObjects];
    }

2.删除数据

//滑动后红色删除按钮上显示的文字
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{

    return @"删除";
}

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

    //删除情况下
    if (editingStyle == UITableViewCellEditingStyleDelete) {

        Person *person = self.dataArray[indexPath.row];
        [self.dataArray removeObject:person];
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];

        //删除CoreData中的数据
        [self.appdelegate.persistentContainer.viewContext deleteObject:person];

        //持久化一下
        [self.appdelegate saveContext];

    }

}

3.修改数据

if ([person.sex isEqualToString:@"男"]) {

    person.sex = @"女";
    person.name = @"新名字";
    [self.appDelegate saveContext];

    }

4.查询数据

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.appdelegate.persistentContainer.viewContext];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    //谓词搜索
    //    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age = 21", ];
    //    [fetchRequest setPredicate:predicate];
    // Specify how the fetched objects should be sorted
    //排序方法(这里为按照年龄升序排列)
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];

    NSError *error = nil;
    NSArray *fetchedObjects = [self.appdelegate.persistentContainer.viewContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"数据查询错误%@",error);
    }else{

        //查询到之后要你的操作代码
        [self.dataArray removeAllObjects];
        [self.dataArray addObjectsFromArray:fetchedObjects];
        [self.tableView reloadData];
    }

以上就是CoreData的增删改查操作,以前习惯了SQLite的使用,乍一用CoreData,觉得比SQLite还简便。附上demo地址:
https://github.com/ZJQian/CoreDataDemo/tree/master

共同学习,共同进步!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值