CoreData之FetchRequestController✨

  • 版权声明:本文为博主原创文章,未经博主允许不得转载。

我目前的理解,CoreData相当于一个综合的数据存储和管理中心,它支持sqlite,二进制存储文件两种形式的数据存储。而CoreData提供了存储管理,包括查询、插入、删除、更新、回滚、会话管理、锁管理等一系列数据库操作。另外,开发者还可以在xcode中使用 .xcdatamodel 扩展名的文件,以图形化的形式编辑数据模型,这里包括了Entities、Properties、Attributes、Relationships四个概念,这里跟关系型数据库有很大的相似点。

  • 下面来看一下CoreData的框架。

一次来了解一下 PersistentStore、DataModel、PersistentStoreCoordinator、ManagedObjects、ManagedObjectsContext、FetchRequest 这些概念。

PersistentStore

这个是数据真正存储的地方,CodeData提供了两种存储的选择,分别是sqlite和二进制文件。PersistentStore本身并不是objc类,仅仅是数据存储。

DataModel

对应的objc类为 NSManagedObjectModel,一个典型的应用如:

/** 
Returns the managed object model for the application. 
If the model doesn't already exist, it is created by merging all of the models 
found in the application bundle. 
*/  
- (NSManagedObjectModel *)managedObjectModel
 {  
  if (managedObjectModel != nil) 
  {  
    return managedObjectModel;  
  }  
managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];  

return managedObjectModel;  
}  ```

这里用了iPhone开发中典型的laze loading,而:

```objc
managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];  

中的nil表示连接项目中所有的 .xcodemodel 文件为一个datamodel,这是一个非常好的方法,把多个entity放在各自的xcodemodel文件中分开管理,然后用这个函数连接起来生成一个datamodel,这样就可以对应一个persistentStore。

PersistentStoreCoordinator

对应的objc类为NSPersistentStoreCoordinator,这个类用来控制对PersistentStore的访问。PersistentStoreCoordinator提供了一些列的高级调用供其他类来使用,对PersistentStore进行读和写。下面看一段典型的代码:

/** 
Returns the persistent store coordinator for the application. 
If the coordinator doesn't already exist, it is created and the application's store 
added to it. 
*/  
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator 
{  
    if (persistentStoreCoordinator != nil) 
    {  
        return persistentStoreCoordinator;  
    }  
    NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory]  
    stringByAppendingPathComponent: @"CoreData.sqlite"]];  
    NSError *error;  
    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]  
    initWithManagedObjectModel: [self managedObjectModel]];  
    
    if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType  
    configuration:nil URL:storeUrl options:nil error:&error]) 
    {  
      // Handle error  
    }  
    return persistentStoreCoordinator;  
} ```

这里默认存储形式为sqlite,并且存储文件为CoreData.sqlite,这段代码比较简单,创建了persistentStoreCoordinator实例。



###ManagedObjects

对应的类为NSManagedObject。上面的CoreData框架图中有Entities,Entity定义了数据的结构,但他并不是数据,真正的数据实例是NSManagedObject类或他的子类。


NSManagedObject类支持Key-Value 编码(KVC),像NSDictionary差不多。NSManagedObject提供了valueForKey:和setValue:forKey:用来设置和查询的方法。另外他也提供了对关系操作的方法。
   下面是几个典型的代码案例:

```swift
NSDate *timeStamp = [managedObject valueForKey:@"timeStamp"];  
[managedObject setValue:[NSDate date] forKey:@"timeStamp"];  

另外KVC也支持keypath,如有两个数据entity,一个是Employee,一个事Employer,Employee中有个属性石whereIWork,而这个属性用relationship连接到了对应的Employer,Employer中有个属性石name,这样要查询一个Employer的name,可以用keypath的形式,whereIWork.name

NSString *employerName = [managedObject valueForKeyPath:@"whereIWork.name"];  

ManagedObjectsContext

对应的类为NSManagedObjectsContext。 这个类是一个用户对persistentStore操作的网关,他维护了用户创建或者加载的managed objects。他记录了用户对managed objects的所有改变,以便用来undo或redo,另外当用户要存储现在的managed objects到persistentstore时,只需调用managedObjectsContext的save方法就行了。

每个应用至少需要一个context,当然可以同时存在多个context,比如多线程时,如NSOperationQueue。context并不是线程安全的,因此在这种情况中用户要自己做好安全工作。

下面是一个简单应用实例。

/** 
Returns the managed object context for the application. 
If the context doesn't already exist, it is created and bound to the persistent 
store coordinator for the application. 
*/  
- (NSManagedObjectContext *) managedObjectContext 
{  
    if (managedObjectContext != nil) 
    {  
        return managedObjectContext;  
    }  
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];  

    if (coordinator != nil) 
    {  
        managedObjectContext = [[NSManagedObjectContext alloc] init];  
        [managedObjectContext setPersistentStoreCoordinator: coordinator];  
    }  
    return managedObjectContext;  
}  ```


这个代码也比较简单,不做解释了。


###FetchRequest(FetchRequestController)
 
这里重点讲FetchRequestController,其实用户打交道最多的就是这个控制器了。要讲的东西很多,放到下面一篇吧。

这篇文章重点讲讲CoreData的Fetched Results Controller。
             
对应的objc类为NSFetchedResultsController。这个类是用来管理CoreData Fetch request返回的对象的。
             
在创建这个控制器之前,必须先创建fetch request。 fetch request描述了详细的查询规则,还可以添加查询结果的排序描述(sort descriptor)。fetchResultsController根据已经创建完的fetch request来创建, 它是NSFetchedResultsController的实例,这个实例的主要任务就是使用fetch request来保证它所关联的数据的新鲜性。创建了fetchResultsController实例后要做一下初始化,一般初始化是向这个控制器发送PerformFetch消息,下面是这一过程的代码。



```swift
- (NSFetchedResultsController *)fetchedResultsController 
{    
    if (fetchedResultsController != nil)
    {    
        return fetchedResultsController;    
    }    
    /*  
    Set up the fetched results controller.  
    */    
    // Create the fetch request for the entity.    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];    
    // Edit the entity name as appropriate.    
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event"    
    inManagedObjectContext:managedObjectContext];    
    [fetchRequest setEntity:entity];    
    // Set the batch size to a suitable number.    
    [fetchRequest setFetchBatchSize:20];    
    // Edit the sort key as appropriate.    
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]    
    initWithKey:@"timeStamp" ascending:NO];    
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor,nil];    
    [fetchRequest setSortDescriptors:sortDescriptors];    
    // Edit the section name key path and cache name if appropriate.    
    // nil for section name key path means "no sections".    
    NSFetchedResultsController *aFetchedResultsController =    
    [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest    
    managedObjectContext:managedObjectContext sectionNameKeyPath:nil    
    cacheName:@"Root"];    
    aFetchedResultsController.delegate = self;    
    self.fetchedResultsController = aFetchedResultsController;    
    [aFetchedResultsController release];    
    [fetchRequest release];    
    [sortDescriptor release];    
    [sortDescriptors release];    
    return fetchedResultsController;    
}    ```



这个函数用来创建FetchedResultsController,过程还是比较简单的,下面是初始化这个控制器代码。

```swift
NSError *error = nil;    
if(![[self  fetchedResultsController]performFetch: &error])
{    
    //handle the error appropriately    
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);    
    exit(-1);    
}    ```



这段代码一般会放在viewDidLoad函数中,初始化之后,fetchedResultsController就与数据相连接了,之后要取数据都能直接从这个控制器提供的方法中去取。
            
实现这个控制器,最关键的还要实现Fetched Results Controller Delegate Methods。控制器与数据源连接后,控制器监视器会时刻监视着数据源,当数据源发生改变后,监视器会调用对应的协议方法,改协议总共要实现四个方法,分别为:

```swift
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller;    
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller;    
- (void)controller:(NSFetchedResultsController *)controller    
   didChangeObject:(id)anObject    
       atIndexPath:(NSIndexPath *)indexPath    
     forChangeType:(NSFetchedResultsChangeType)type    
      newIndexPath:(NSIndexPath *)newIndexPath;    
- (void)controller:(NSFetchedResultsController *)controller    
  didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo    
           atIndex:(NSUInteger)sectionIndex    
     forChangeType:(NSFetchedResultsChangeType)type;    

下面依次来解释这四个协议方法。

1. - (void)controllerWillChangeContent:(NSFetchedResultsController *)controller;

当控制器监控的数据发生改变时,如对象被删除,有插入,更新等,监视器会在数据发生改变前意识到这个情况,此时就会调用这个函数。往往我们用列表的形式表现数据,此时意味着屏幕上的数据即将过时,因为数据马上要改变了,这是这个协议方法的工作就是通知列表数据马上要更新的消息,往往代码是这样实现的。

- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller 
{    
    [self.tableView beginUpdates];    
}  ```


######2. - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller;
            
当fetchedResultsController完成对数据的改变时,监视器会调用这个协议方法。在上面提到的情况,这个方法要通知列表数据已经完成,可以更新显示的数据这个
消息,因此通常的实现是这样的。


```swift
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{    
    [self.tableView endUpdates];    
}   ```


######3. - (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath;


当fetchedResultsController发现指定的对象有改变时,监视器会调用这个协议方法。这里改变的类型从列表中体现有 更新、插入、删除或者行的移动。因此这个
方法要实现所有的这些方法,以应对任何一种改变。下面是这个方法的标准实现。

```swift
- (void)controller:(NSFetchedResultsController *)controller    
   didChangeObject:(id)anObject    
       atIndexPath:(NSIndexPath *)indexPath    
     forChangeType:(NSFetchedResultsChangeType)type    
      newIndexPath:(NSIndexPath *)newIndexPath 
{    
    switch(type) 
    {    
        case NSFetchedResultsChangeInsert:    
            [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]     
                            withRowAnimation:UITableViewRowAnimationFade];    
            break;    
        case NSFetchedResultsChangeDelete:    
            [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]    
                            withRowAnimation:UITableViewRowAnimationFade];    
            break;    
        case NSFetchedResultsChangeUpdate: 
        {    
            NSString *sectionKeyPath = [controller sectionNameKeyPath];    
            if (sectionKeyPath == nil)    
                break;    
            NSManagedObject *changedObject = [controller objectAtIndexPath:indexPath];    
            NSArray *keyParts = [sectionKeyPath componentsSeparatedByString:@"."];    
            id currentKeyValue = [changedObject valueForKeyPath:sectionKeyPath];    
            for (int i = 0; i < [keyParts count] - 1; i++) 
            {    
                NSString *onePart = [keyParts objectAtIndex:i];    
                changedObject = [changedObject valueForKey:onePart];    
            }    
            sectionKeyPath = [keyParts lastObject];    
            NSDictionary *committedValues = [changedObject committedValuesForKeys:nil];    
            if ([[committedValues valueForKeyPath:sectionKeyPath]isEqual:currentKeyValue])    
                break;    
            NSUInteger tableSectionCount = [self.tableView numberOfSections];    
            NSUInteger frcSectionCount = [[controller sections] count];    
            if (tableSectionCount != frcSectionCount) 
            {    
                // Need to insert a section    
                NSArray *sections = controller.sections;    
                NSInteger newSectionLocation = -1;    
                for (id oneSection in sections) {    
                    NSString *sectionName = [oneSection name];    
                    if ([currentKeyValue isEqual:sectionName]) 
                    {    
                        newSectionLocation = [sections indexOfObject:oneSection];    
                        break;    
                    }    
                }    
                if (newSectionLocation == -1)    
                    return; // uh oh    
                if (!((newSectionLocation == 0) && (tableSectionCount == 1)    
                       && ([self.tableView numberOfRowsInSection:0] == 0)))    
                    [self.tableView insertSections:[NSIndexSet indexSetWithIndex:newSectionLocation]    
                                  withRowAnimation:UITableViewRowAnimationFade];    
                NSUInteger indices[2] = {newSectionLocation, 0};    
                newIndexPath = [[[NSIndexPath alloc] initWithIndexes:indiceslength:2] autorelease];    
            }    
        }    
        case NSFetchedResultsChangeMove    
            if (newIndexPath != nil) 
            {    
                [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]    
                                      withRowAnimation:UITableViewRowAnimationFade];    
                [self.tableView insertRowsAtIndexPaths: [NSArray arrayWithObject:newIndexPath]    
                                      withRowAnimation: UITableViewRowAnimationRight];    
            }    
            else 
            {    
                [self.tableView reloadSections:[NSIndexSet    
                indexSetWithIndex:[indexPath section]]withRowAnimation:UITableViewRowAnimationFade];    
            }    
            break;    
        default:    
            break;    
    }    
}    ```

          
从上面的代码可以看出,插入,删除,移动是比较简单的,最复杂的是更新。这个代码是xcode的模板代码,基本能适用我们遇到的情况,对更新里面的代码我还不是非常确定,所以这里留着等过几天完全吃透了再补上。


######4. - (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type;

              
当改变控制器管理的对象后引起了列表section的变化,此时监视器就会调用这个协议函数。
            
下面是标准实现。 

```swift
- (void)controller:(NSFetchedResultsController *)controller    
  didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo    
           atIndex:(NSUInteger)sectionIndex    
     forChangeType:(NSFetchedResultsChangeType)type 
{    
    switch(type) 
    {    
        case NSFetchedResultsChangeInsert:    
            if (!((sectionIndex == 0) && ([self.tableView numberOfSections] == 1)    
                             && ([self.tableView numberOfRowsInSection:0] == 0)))    
                [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex]    
                              withRowAnimation:UITableViewRowAnimationFade];    
            break;    
        case NSFetchedResultsChangeDelete:    
            if (!((sectionIndex == 0) && ([self.tableView numberOfSections] == 1)    
                             && ([self.tableView numberOfRowsInSection:0] == 0)))    
                [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex]    
                              withRowAnimation:UITableViewRowAnimationFade];    
            break;    
        case NSFetchedResultsChangeMove:    
        case NSFetchedResultsChangeUpdate:    
        default:    
            break;    
    }    
}    ```
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,390评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,821评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,632评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,170评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,033评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,098评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,511评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,204评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,479评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,572评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,341评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,893评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,171评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,486评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,676评论 2 335

推荐阅读更多精彩内容