您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 數據持久化:NSFetchedResultsController 詳解

編輯:iOS 開發綜合

NSFetchedResultsController 與 UITableView 搭配使用,在資料處理上有極強的靈活性。最直接的好處是不用手動分頁:傳統做法得先撈出總筆數,再在記憶體中過濾,等於做了兩次操作,資料量大時記憶體消耗可觀,處理不當甚至會讓 App 直接崩潰。

改用 NSFetchedResultsController 之後,程式碼更簡單、效能也更好。它會自動幫你管理批次載入(fetch batch),取得對應的 Core Data 物件同樣輕鬆。

更關鍵的一點是:當你在別的介面新增、修改或刪除資料時,它能自動同步刷新 UITableView。讓列表與資料庫保持一致,這件事從此變得非常簡單。

建立 fetchedResultsController

/*
 * NSFetchedResultsController 的輸入是一個獲取請求(fetch request)與一個上下文(context),
 * 當請求結果中的資料發生變化時,它會呼叫自身的代理方法。
 */
- (NSFetchedResultsController *)fetchedResultsController {
    NSLog(@"fetchedResultsController");

    // 先檢查是否已經建立過
    if (_fetchedResultsController != nil) {
        return _fetchedResultsController;
    }

    // 可以將獲取請求視為 SQL 的 SELECT 語句
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

    // 依據上下文中的 Event 實體建立 entity description
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event"
                                              inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];

    // 設定批次大小,控制一次載入的筆數
    [fetchRequest setFetchBatchSize:20];

    // 排序描述符相當於 SQL 的 ORDER BY,這裡以 timeStamp 欄位降序
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"timeStamp" ascending:NO];
    NSArray *sortDescriptors = @[sortDescriptor];
    [fetchRequest setSortDescriptors:sortDescriptors];

    NSFetchedResultsController *aFetchedResultsController =
        [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                            managedObjectContext:self.managedObjectContext
                                              sectionNameKeyPath:nil
                                                       cacheName:@"Master"];
    aFetchedResultsController.delegate = self;
    self.fetchedResultsController = aFetchedResultsController;

    NSError *error = nil;
    if (![self.fetchedResultsController performFetch:&error]) {
        // 正式環境請替換成合適的錯誤處理,abort() 僅適合開發階段除錯使用
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    return _fetchedResultsController;
}

代理方法:通知即將開始變更

- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
    NSLog(@"controllerWillChangeContent");
    // 告訴表格:一連串更新即將發生
    [self.tableView beginUpdates];
}

代理方法:Section 層級的變化

- (void)controller:(NSFetchedResultsController *)controller
   didChangeSection:(id<NSFetchedResultsSectionInfo>)sectionInfo
            atIndex:(NSUInteger)sectionIndex
      forChangeType:(NSFetchedResultsChangeType)type {
    switch (type) {
        case NSFetchedResultsChangeInsert:
            [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex]
                          withRowAnimation:UITableViewRowAnimationFade];
            break;
        case NSFetchedResultsChangeDelete:
            [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex]
                          withRowAnimation:UITableViewRowAnimationFade];
            break;
        default:
            return;
    }
}

代理方法:單筆物件的變化

- (void)controller:(NSFetchedResultsController *)controller
       didChangeObject:(id)anObject
        atIndexPath:(NSIndexPath *)indexPath
      forChangeType:(NSFetchedResultsChangeType)type
       newIndexPath:(NSIndexPath *)newIndexPath {
    UITableView *tableView = self.tableView;
    switch (type) {
        case NSFetchedResultsChangeInsert:
            [tableView insertRowsAtIndexPaths:@[newIndexPath]
                            withRowAnimation:UITableViewRowAnimationFade];
            break;
        case NSFetchedResultsChangeDelete:
            [tableView deleteRowsAtIndexPaths:@[indexPath]
                            withRowAnimation:UITableViewRowAnimationFade];
            break;
        case NSFetchedResultsChangeUpdate:
            [self configureCell:[tableView cellForRowAtIndexPath:indexPath]
                   atIndexPath:indexPath];
            break;
        case NSFetchedResultsChangeMove:
            [tableView deleteRowsAtIndexPaths:@[indexPath]
                            withRowAnimation:UITableViewRowAnimationFade];
            [tableView insertRowsAtIndexPaths:@[newIndexPath]
                            withRowAnimation:UITableViewRowAnimationFade];
            break;
    }
}

代理方法:變更結束

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
    NSLog(@"controllerDidChangeContent");
    // 告訴表格視圖:更新流程結束
    [self.tableView endUpdates];
}

整套機制的價值在於「宣告式」:你只要描述想要什麼資料、怎麼排序,剩下的批次載入、增量更新、動畫刷新都由系統代勞,不必再手寫一堆 reloadData 與索引校正的程式碼。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved