通常情况下,CoreData 的增删改查操作都在主线程上执行,那么对数据库的操作就会影响到 UI 操作,这在操作的数据量比较小的时候,执行的速度很快,我们也不会察觉到对 UI 的影响,但是当数据量特别大的时候,再把 CoreData 的操作放到主线程中就会影响到 UI 的流畅性。自然而然地我们就会想到使用后台线程来处理大量的数据操作。 使用后台 managedObjectContextCoreData 里使用后台更新数据最常用的方案是一个 NSManagedObjectContext *backgroundContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
backgroundContext.persistentStoreCoordinator = self.persistentStoreCoordinator; 在最新的 iOS 10 中,CoreData 栈的创建被封装在了 NSManagedObjectContext *backgroundContext = ((AppDelegate *)[UIApplication sharedApplication].delegate).persistentContainer.newBackgroundContext; 另外,后台 [self.backgroundContext performBlock:^{
for (NSUInteger i = 0; i < 100000; i ) {
NSString *name = [NSString stringWithFormat:@'student-%d', arc4random_uniform(9999)];
int16_t age = arc4random_uniform(10) 10;
int16_t stuId = arc4random_uniform(9999);
Student *student = [NSEntityDescription insertNewObjectForEntityForName:@'Student' inManagedObjectContext:self.backgroundContext];
student.studentName = name;
student.studentAge = age;
student.studentId = stuId;
}
NSError *error;
[self.backgroundContext save:&error];
[self.logger dealWithError:error
whenFail:@'failed to insert'
whenSuccess:@'insert success'];
}]; 后台插入数据之后,还没有完,因为数据是通过后台的 NSManagedObjectContextDidSaveNotification-w600
收到通知之后,只需要调用 下面是示例代码: - (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveContextSave:) name:NSManagedObjectContextDidSaveNotification object:self.backgroundContext];
}
- (void)doSometingInsertingInBackground {
// backgroundContext ....
}
- (void)receiveContextSave:(NSNotification *)note {
[self.context mergeChangesFromContextDidSaveNotification:note];
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
} 注意:通知的 - (void)receiveContextSave:(NSNotification *)note {
[self.context mergeChangesFromContextDidSaveNotification:note];
NSSet<Student *> *managedObjects = note.userInfo[NSInsertedObjectsKey];
NSManagedObjectID *studentId = managedObjects.allObjects[0].objectID;
[self.context performBlock:^{
// 这是错的
// Student *wrongStudent = managedObjects.allObjects[0];
// 应该这么做
Student *student = [self.context objectWithID:studentId];
// modify student...
}];
} 著作权归作者所有
|
|
来自: 永恒clek4xeu0r > 《ios》