iOS Xcode8下CoreData的简单应用

来源:互联网 发布:知乎 农村金融数据 编辑:程序博客网 时间:2024/05/17 04:09

原来没怎么使用过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

共同学习,共同进步!

0 0
原创粉丝点击