使用NSFetchedResultsController时,UICollectionView滚动不顺畅

时间:2014-05-09 05:05:26

标签: ios objective-c core-data uicollectionview nsfetchedresultscontroller

我正在使用 UICollectionView NSFetchResultsController 来展示不同的照片集。这是我第一次使用 UICollectionView & NSFetchResultsController

这是我的代码:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"CellIdentifier";
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];

    MyPhoto *myPhoto = [self.fetchedResultsController objectAtIndexPath:indexPath];

    cell.imageView.image = [UIImage imageWithData:myPhoto.photoData];

    return cell;
}


- (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];

        NSManagedObjectContext *moc = [[CoreDataManager sharedInstance] managedObjectContext];

        // Edit the entity name as appropriate.
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyPhoto" inManagedObjectContext:moc];
    [fetchRequest setEntity:entity];

    // Set the batch size to a suitable number.
    [fetchRequest setFetchBatchSize:40];

    // Sort using the timeStamp property.
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"sectionName" ascending:YES];
    NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc] initWithKey:@"timeStamp" ascending:YES];
    [fetchRequest setSortDescriptors:@[sortDescriptor, sortDescriptor1]];

        // Use the folderName property to group into sections.
         _fetchedResultsController = [[NSFetchedResultsController alloc]  initWithFetchRequest:fetchRequest managedObjectContext:moc sectionNameKeyPath:@"sectionName" cacheName:@"Root"];
        _fetchedResultsController.delegate = self;

    return _fetchedResultsController;
}    

当我有更多部分并尝试滚动视图时,它不能平滑滚动。 我错过了什么吗?

1 个答案:

答案 0 :(得分:2)

将NSFetchedResultController与TableView或CollectionView一起使用没有区别。

我在你的代码中看到的东西很少 -
1)BatchSize:40 - 批量越大,获取的时间越长。它不会经常使用,但需要更多时间。例如,尝试将其设置为20。滚动应该是扼要的。

2)你的实体是照片。
- 确保不要将BLOB(大数据)存储为值。这将使得取得缓慢。如果您需要在模型中的CoreData集(存储在外部存储文件中)中存储图像。
- 制作图像缩略图。如果您需要显示小尺寸图像,请制作缩略图并将其直接保存到CoreData(不要使用"存储在外部存储文件")键。这个vill非常快,因为你不会使用任何外部文件和Photo填充的大小很小 - 预取数据。如果你有一些子照片,如果照片和你正在使用它们,

NSString *relationshipKeyPath = @"bObjects"; // Set this to the name of the relationship on photo
NSArray *keyPaths = [NSArray arrayWithObject:relationshipKeyPath];
[request setRelationshipKeyPathsForPrefetching:keyPaths];