我有一个示例应用,其中包含一个NSManagedObject
(让我们称之为类CustomObject
),只有一个属性。
该应用有一个简单的用户界面,其中包含一个UICollectionView
视图控制器,使用NSFetchedResultsController
作为基础数据源。 NSFetchedResultsController
也设置为使用视图控制器作为NSFetchedResultsControllerDelegate
委托。此外,我还有一些工具栏,其中包含一些按钮,用于添加/删除CustomObject
个项目。
一个按钮将导致创建10,000 CustomObject
个实体。我希望能够按下此按钮,一旦实体保存到磁盘/准备使用,UICollectionView
应该更新以反映新值。我100%意识到会有某种延迟 - 像这样的保存值不是即时的 - 我希望在后台线程上发生延迟以防止UI锁定!
尽管我从我能说的内容中正确设置,但每当我实现三个“重要”NSFetchedResultsControllerDelegate
方法中的任何一个时,我都会遇到UI延迟。 UI滞后持续时间根据数据存储中的CustomObject
个数而有所不同。例如,如果我刚刚添加了前10,000个,则只有少量滞后,不到1秒。如果我已经添加了50,000 CustomObject
s,则滞后更加明显,并且在某些情况下持续超过5-10秒。
正如我所说,当我实施controllerWillChangeContent
,controller:didChangeObject:atIndexPath:forChangeType:newIndexPath
或controllerDidChangeContent
方法时,UI滞后才出现。即使在方法中没有实际实现,只是它在视图控制器中的事实使插入变慢。
知道我做错了什么吗?有没有解决的办法?这是一些代码:
CoreDataController.m - 负责设置核心数据堆栈
//
// CoreDataController.m
// CoreDataTestApp
//
// Created by ZOlbrys on 4/12/18.
// Copyright © 2018 ZOlbrys. All rights reserved.
//
#import "CoreDataController.h"
#import <UIKit/UIKit.h>
@interface CoreDataController()
@property (nonatomic, strong) NSURL *persistentStoreURL;
@property (nonatomic, strong) NSURL *managedObjectModelURL;
@property (nonatomic, strong, readwrite) NSPersistentStoreCoordinator *persistentStoreCoordinator;
@property (nonatomic, strong) NSManagedObjectModel *managedObjectModel;
@property (nonatomic, strong, readwrite) NSManagedObjectContext *managedObjectContext;
@end
@implementation CoreDataController
+ (CoreDataController *)sharedController {
static CoreDataController *sharedController;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSURL *managedObjectModelURL = [NSURL fileURLWithPath:[[NSBundle bundleForClass:[self class]] pathForResource:@"CoreDataTestApp" ofType:@"momd"]];
NSString *applicationDocumentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSURL *persistentStoreURL = [NSURL fileURLWithPath:[applicationDocumentsDirectory stringByAppendingPathComponent:@"CoreDataTestApp.sqlite"]];
sharedController = [[CoreDataController alloc] initWithManagedObjectModelURL:managedObjectModelURL persistentStoreURL:persistentStoreURL];
});
return sharedController;
}
- (instancetype)initWithManagedObjectModelURL:(NSURL*)managedObjectModelURL persistentStoreURL:(NSURL*)persistentStoreURL {
self = [super init];
if (self) {
self.persistentStoreURL = persistentStoreURL;
self.managedObjectModelURL = managedObjectModelURL;
[self setupCoreDataStack];
}
return self;
}
- (void)setupCoreDataStack {
// setup managed object model
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:self.managedObjectModelURL];
// setup persistent store coordinator
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.managedObjectModel];
[_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:self.persistentStoreURL options:nil error:nil];
// setup MOC
_managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[_managedObjectContext setPersistentStoreCoordinator:self.persistentStoreCoordinator];
}
@end
ViewController.m - 负责,查看控制器的东西!
//
// ViewController.m
// CoreDataTestApp
//
// Created by ZOlbrys on 4/12/18.
// Copyright © 2018 ZOlbrys. All rights reserved.
//
#import "ViewController.h"
#import "CustomCell.h"
#import "CoreDataController.h"
#import "CustomObject+CoreDataClass.h"
static NSString *const CUSTOM_CELL_REUSE_IDENTIFIER = @"CUSTOM_CELL_REUSE_IDENTIFIER";
@interface ViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, NSFetchedResultsControllerDelegate>
@property (strong, nonatomic) IBOutlet UICollectionView *collectionView;
@property (strong, nonatomic) NSFetchedResultsController *fetchedResultsController;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.collectionView.dataSource = self;
self.collectionView.delegate = self;
[self setupFetchedResultsController];
}
- (void)setupFetchedResultsController {
NSFetchRequest<CustomObject *> *fetchRequest = [CustomObject fetchRequest];
fetchRequest.sortDescriptors = @[ [[NSSortDescriptor alloc] initWithKey:@"identifier" ascending:YES] ];
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[CoreDataController sharedController].managedObjectContext sectionNameKeyPath:nil cacheName:nil];
self.fetchedResultsController.delegate = self;
[self.fetchedResultsController performFetch:nil];
[self.collectionView reloadData];
}
- (void)addObjects:(NSUInteger)objectCount {
NSManagedObjectContext *temporaryContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
temporaryContext.parentContext = [CoreDataController sharedController].managedObjectContext;
[temporaryContext performBlock:^{
for (int i = 0; i < objectCount; i++) {
CustomObject *object = [NSEntityDescription insertNewObjectForEntityForName:@"CustomObject" inManagedObjectContext:temporaryContext];
object.identifier = [[NSUUID UUID] UUIDString];
}
NSError *error;
if (![temporaryContext save:&error]) {
NSLog(@"Error: %@", error);
}
[[CoreDataController sharedController].managedObjectContext performBlock:^{
NSError *error;
if (![[CoreDataController sharedController].managedObjectContext save:&error]) {
NSLog(@"Error: %@", error);
}
}];
}];
}
- (void)removeObjects:(NSUInteger)objectCount {
NSManagedObjectContext *temporaryContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
temporaryContext.parentContext = [CoreDataController sharedController].managedObjectContext;
[temporaryContext performBlock:^{
NSFetchRequest<CustomObject *> *fetchRequest = [CustomObject fetchRequest];
fetchRequest.sortDescriptors = @[ [[NSSortDescriptor alloc] initWithKey:@"identifier" ascending:YES] ];
fetchRequest.fetchLimit = objectCount;
NSFetchedResultsController<CustomObject *> *fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:temporaryContext sectionNameKeyPath:nil cacheName:nil];
[fetchedResultsController performFetch:nil];
for (CustomObject *object in fetchedResultsController.fetchedObjects) {
[temporaryContext deleteObject:object];
}
NSError *error;
if (![temporaryContext save:&error]) {
NSLog(@"Error: %@", error);
}
[[CoreDataController sharedController].managedObjectContext performBlock:^{
NSError *error;
if (![[CoreDataController sharedController].managedObjectContext save:&error]) {
NSLog(@"Error: %@", error);
}
}];
}];
}
- (IBAction)add10k:(id)sender {
[self addObjects:10000];
}
- (IBAction)add1:(id)sender {
[self addObjects:1];
}
- (IBAction)refetchData:(id)sender {
[self.fetchedResultsController performFetch:nil];
[self.collectionView reloadData];
}
- (IBAction)remove1:(id)sender {
[self removeObjects:1];
}
- (IBAction)remove10k:(id)sender {
[self removeObjects:10000];
}
#pragma mark UICollectionViewDataSource
- (NSInteger)collectionView:(nonnull UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return [self.fetchedResultsController.sections objectAtIndex:section].numberOfObjects;
}
- (nonnull __kindof UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
CustomCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:CUSTOM_CELL_REUSE_IDENTIFIER forIndexPath:indexPath];
[cell setDisplayText:@"TODO"];
cell.backgroundColor = [UIColor blueColor];
return cell;
}
#pragma mark NSFetchedResultsControllerDelegate
//- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
// // TODO
//}
//
//- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath {
// // TODO
//}
//
//- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
// // TODO
//}
@end
当然,我做了一些分析 - 上面没有注释controllerWillChangeContent
,我看到了:
这不是我的代码 - 它是内部Apple代码......
这是显示此问题的项目的github链接:
答案 0 :(得分:1)
滞后似乎与所选的核心数据堆栈有关:
[协调员]←[主要背景]←[私人背景]
使用此体系结构,私有上下文中的每个提取/保存操作都将通过主上下文进行,然后阻止UI。更好的选择可能是交换上下文:
[协调员]←[私人语境]←[主要背景]
这一次,私有上下文操作不会阻止UI。
另一个选择是将两个上下文绑定到协调器:
[私人语境]→[协调员]←[主要背景]
使用这两种解决方案,如果需要,您需要将更新的对象合并回主要上下文,以便&#34;参见&#34;来自UI的变化。