iOS App中数据管理框架Core Data的基本数据操作教程

2020-01-15 15:20:58王旭

    NSLog(@"%@",[res.firstObject stuNum]);

进行数据初始化

    NSFetchedResultsController的初始化需要一个查询请求和一个数据操作上下文。代码示例如下:

//遵守协议
@interface ViewController ()<NSFetchedResultsControllerDelegate>
{
    //数据桥接对象
    NSFetchedResultsController * _fecCon;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //进行初始化操作
    NSURL *modelUrl = [[NSBundle mainBundle]URLForResource:@"Model" withExtension:@"momd"];
    NSManagedObjectModel * mom = [[NSManagedObjectModel alloc]initWithContentsOfURL:modelUrl];
    NSPersistentStoreCoordinator * psc = [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:mom];
    NSURL * path =[NSURL fileURLWithPath:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"CoreDataExample.sqlite"]];
    [psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:path options:nil error:nil];
    NSManagedObjectContext * moc = [[NSManagedObjectContext alloc]initWithConcurrencyType:NSMainQueueConcurrencyType];
    [moc setPersistentStoreCoordinator:psc];
    NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName:@"SchoolClass"];
    //设置数据排序
    [request setSortDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"stuNum" ascending:YES]]];
    //进行数据桥接对象的初始化
    _fecCon = [[NSFetchedResultsController alloc]initWithFetchRequest:request managedObjectContext:moc sectionNameKeyPath:nil cacheName:nil];
    //设置代理
    _fecCon.delegate=self;
    //进行数据查询
    [_fecCon performFetch:nil];
}
@end

用于初始化NSFecthedResultsController的数据请求对象必须设置一个排序规则。在initWithFetchRequest:managedObjectContext:sectionNameKeyPath:cacheName:方法中,如果设置第三个参数,则会以第三个参数为键值进行数据的分区。当数据发生变化时,将通过代理进行方法的回调。

三、与UITableView进行数据绑定

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cellid"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cellid"];